import*as e from"../../core/i18n/i18n.js";import*as t from"../../ui/legacy/legacy.js";import*as i from"../../core/common/common.js";import*as o from"../../core/sdk/sdk.js";import*as n from"../../third_party/codemirror.next/codemirror.next.js";import*as r from"../../ui/components/icon_button/icon_button.js";import*as s from"../../ui/components/text_editor/text_editor.js";import*as a from"../../core/host/host.js";import*as c from"../../core/platform/platform.js";import{assertNotNullOrUndefined as l}from"../../core/platform/platform.js";import*as d from"../../models/bindings/bindings.js";import*as u from"../../models/persistence/persistence.js";import*as h from"../../models/source_map_scopes/source_map_scopes.js";import*as p from"../../ui/legacy/components/source_frame/source_frame.js";import*as g from"../coverage/coverage.js";import*as m from"../../ui/legacy/components/color_picker/color_picker.js";import*as b from"../../ui/legacy/components/inline_editor/inline_editor.js";import*as f from"../../models/breakpoints/breakpoints.js";import*as S from"../../models/text_utils/text_utils.js";import*as v from"../../models/workspace/workspace.js";import*as C from"../../ui/legacy/components/object_ui/object_ui.js";import*as w from"./components/components.js";import*as I from"../../core/root/root.js";import*as x from"../../models/extensions/extensions.js";import*as y from"../snippets/snippets.js";import*as E from"../search/search.js";import*as k from"../../ui/legacy/components/quick_open/quick_open.js";import*as T from"../../models/issues_manager/issues_manager.js";import*as L from"../../ui/components/issue_counter/issue_counter.js";import*as M from"../../ui/legacy/components/utils/utils.js";import*as P from"../../models/formatter/formatter.js";import{iconDataForResourceType as F}from"../utils/utils.js";import*as D from"../../ui/components/linear_memory_inspector/linear_memory_inspector.js";const N=new CSSStyleSheet;N.replaceSync(':host{padding:10px}.widget{align-items:center}label{white-space:nowrap}input[type="text"].add-source-map{box-shadow:0 0 0 1px var(--box-shadow-outline-color);font-size:inherit;margin:0 8px 0 5px}\n/*# sourceURL=dialog.css */\n');const A={sourceMapUrl:"Source map URL: ",debugInfoUrl:"DWARF symbols URL: ",add:"Add"},U=e.i18n.registerUIStrings("panels/sources/AddSourceMapURLDialog.ts",A),R=e.i18n.getLocalizedString.bind(void 0,U);class B extends t.Widget.HBox{input;dialog;callback;constructor(e,i){super(!0),this.contentElement.createChild("label").textContent=e,this.input=t.UIUtils.createInput("add-source-map","text"),this.input.addEventListener("keydown",this.onKeyDown.bind(this),!1),this.contentElement.appendChild(this.input);const o=t.UIUtils.createTextButton(R(A.add),this.apply.bind(this));this.contentElement.appendChild(o),this.dialog=new t.Dialog.Dialog,this.dialog.setSizeBehavior("MeasureContent"),this.dialog.setDefaultFocusedElement(this.input),this.callback=i}static createAddSourceMapURLDialog(e){return new B(R(A.sourceMapUrl),e)}static createAddDWARFSymbolsURLDialog(e){return new B(R(A.debugInfoUrl),e)}show(){super.show(this.dialog.contentElement),this.dialog.show()}done(e){this.dialog.hide(),this.callback(e)}apply(){this.done(this.input.value)}onKeyDown(e){"Enter"===e.key&&(e.consume(!0),this.apply())}wasShown(){super.wasShown(),this.registerCSSFiles([N])}}var V=Object.freeze({__proto__:null,AddDebugInfoURLDialog:B});const O=new CSSStyleSheet;O.replaceSync(":host{z-index:30;padding:4px;background-color:var(--color-background-elevation-1);border-radius:7px;border:2px solid var(--color-details-hairline);width:90%;pointer-events:auto}:host(.sources-edit-breakpoint-dialog){border-radius:0;z-index:30;background-color:var(--color-background-elevation-1);width:555px;pointer-events:auto;margin-left:-1px;padding:0 10px 10px 5px;border:1px solid var(--color-details-hairline)}:host-context(.sources-edit-breakpoint-dialog) .condition-editor{background-color:var(--color-background);margin:0 6px 20px 3px}:host-context(.sources-edit-breakpoint-dialog) .source-frame-breakpoint-toolbar{font-family:sans-serif;font-size:12px}:host-context(.sources-edit-breakpoint-dialog) .link,\n.devtools-link{font-family:sans-serif;font-size:12px;margin:0 3px}:host-context(.sources-edit-breakpoint-dialog) devtools-icon.link-icon{vertical-align:sub;margin-right:0.5ch}:host-context(.sources-edit-breakpoint-dialog) .link-wrapper{display:inline-flex}:host-context(.sources-edit-breakpoint-dialog) .dialog-header{display:flex;justify-content:space-between;align-items:center}:host-context(.sources-edit-breakpoint-dialog) .dialog-header > devtools-icon:hover{--icon-color:var(--icon-default-hover)}\n/*# sourceURL=breakpointEditDialog.css */\n");const{Direction:W}=s.TextEditorHistory,j={breakpointType:"Breakpoint type",breakpoint:"Breakpoint",closeDialog:"Close edit dialog and save changes",conditionalBreakpoint:"Conditional breakpoint",logpoint:"Logpoint",expressionToCheckBeforePausingEg:"Expression to check before pausing, e.g. x > 5",pauseOnlyWhenTheConditionIsTrue:"Pause only when the condition is true",learnMoreOnBreakpointTypes:"Learn more: Breakpoint Types",logMessageEgXIsX:"Log message, e.g. `'x is', x`",logAMessageToConsoleDoNotBreak:"Log a message to Console, do not break"},H=e.i18n.registerUIStrings("panels/sources/BreakpointEditDialog.ts",j),_=e.i18n.getLocalizedString.bind(void 0,H);class z extends t.Widget.Widget{onFinish;finished;editor;typeSelector;placeholderCompartment;#e;#t;constructor(e,o,a,c){super(!0);const l=[n.javascript.javascriptLanguage,s.Config.baseConfiguration(o||""),s.Config.closeBrackets,s.Config.autocompletion.instance(),n.EditorView.lineWrapping,s.Config.showCompletionHint,s.Config.conservativeCompletion,n.javascript.javascriptLanguage.data.of({autocomplete:e=>this.#t.historyCompletions(e)}),n.autocompletion(),s.JavaScript.argumentHints()];this.onFinish=c,this.finished=!1,this.element.tabIndex=-1,this.element.classList.add("sources-edit-breakpoint-dialog");const d=this.contentElement.createChild("div","dialog-header"),u=new t.Toolbar.Toolbar("source-frame-breakpoint-toolbar",d);u.appendText(`Line ${e+1}:`),this.typeSelector=new t.Toolbar.ToolbarComboBox(this.onTypeChanged.bind(this),_(j.breakpointType)),this.typeSelector.createOption(_(j.breakpoint),"REGULAR_BREAKPOINT");const h=this.typeSelector.createOption(_(j.conditionalBreakpoint),"CONDITIONAL_BREAKPOINT"),p=this.typeSelector.createOption(_(j.logpoint),"LOGPOINT");this.typeSelector.select(a?p:h),u.appendToolbarItem(this.typeSelector);const g=o||"",m=e=>(s.JavaScript.isExpressionComplete(e.state.doc.toString()).then((t=>{t?this.finishEditing(!0,this.editor.state.doc.toString()):n.insertNewlineAndIndent(e)})),!0),b=[{key:"ArrowUp",run:()=>this.#t.moveHistory(-1)},{key:"ArrowDown",run:()=>this.#t.moveHistory(1)},{mac:"Ctrl-p",run:()=>this.#t.moveHistory(-1,!0)},{mac:"Ctrl-n",run:()=>this.#t.moveHistory(1,!0)},{key:"Mod-Enter",run:m},{key:"Enter",run:m},{key:"Shift-Enter",run:n.insertNewlineAndIndent},{key:"Escape",run:()=>(this.finishEditing(!1,""),!0)}];this.placeholderCompartment=new n.Compartment;const f=this.contentElement.appendChild(document.createElement("div"));f.classList.add("condition-editor"),this.editor=new s.TextEditor.TextEditor(n.EditorState.create({doc:g,selection:{anchor:0,head:g.length},extensions:[this.placeholderCompartment.of(this.getPlaceholder()),n.keymap.of(b),l]})),f.appendChild(this.editor);const S=new r.Icon.Icon;S.data={iconName:"cross",color:"var(--icon-default)",width:"20px",height:"20px"},S.title=_(j.closeDialog),S.onclick=()=>this.finishEditing(!0,this.editor.state.doc.toString()),d.appendChild(S),this.#e=new s.AutocompleteHistory.AutocompleteHistory(i.Settings.Settings.instance().createLocalSetting("breakpointConditionHistory",[])),this.#t=new s.TextEditorHistory.TextEditorHistory(this.editor,this.#e);const v=this.contentElement.appendChild(document.createElement("div"));v.classList.add("link-wrapper");const C=t.Fragment.html`<x-link class="link devtools-link" tabindex="0" href="https://goo.gle/devtools-loc">${_(j.learnMoreOnBreakpointTypes)}</x-link>`,w=new r.Icon.Icon;w.data={iconName:"open-externally",color:"var(--icon-link)",width:"16px",height:"16px"},w.classList.add("link-icon"),C.prepend(w),v.appendChild(C),this.updateTooltip()}saveAndFinish(){this.finishEditing(!0,this.editor.state.doc.toString())}focusEditor(){this.editor.editor.focus()}onTypeChanged(){"REGULAR_BREAKPOINT"!==this.breakpointType?(this.editor.dispatch({effects:this.placeholderCompartment.reconfigure(this.getPlaceholder())}),this.updateTooltip()):this.finishEditing(!0,"")}get breakpointType(){const e=this.typeSelector.selectedOption();return e?e.value:null}getPlaceholder(){const e=this.breakpointType;return"CONDITIONAL_BREAKPOINT"===e?n.placeholder(_(j.expressionToCheckBeforePausingEg)):"LOGPOINT"===e?n.placeholder(_(j.logMessageEgXIsX)):[]}updateTooltip(){const e=this.breakpointType;"CONDITIONAL_BREAKPOINT"===e?t.Tooltip.Tooltip.install(this.typeSelector.element,_(j.pauseOnlyWhenTheConditionIsTrue)):"LOGPOINT"===e&&t.Tooltip.Tooltip.install(this.typeSelector.element,_(j.logAMessageToConsoleDoNotBreak))}finishEditing(e,t){if(this.finished)return;this.finished=!0,this.editor.remove(),this.#e.pushHistoryItem(t);const i="LOGPOINT"===this.breakpointType;this.onFinish({committed:e,condition:t,isLogpoint:i})}wasShown(){super.wasShown(),this.registerCSSFiles([O])}get editorForTest(){return this.editor}}var q=Object.freeze({__proto__:null,BreakpointEditDialog:z});const G=new CSSStyleSheet;G.replaceSync('.call-frame-warnings-message{--override-ignore-message-background-color:#ffffc2;text-align:center;font-style:italic;padding:4px;color:var(--color-text-secondary);background-color:var(--override-ignore-message-background-color)}.ignore-listed-message{padding:1px}.ignore-listed-message-label{color:var(--color-text-secondary);align-items:center;display:flex}.-theme-with-dark-background .ignore-listed-message,\n:host-context(.-theme-with-dark-background) .ignore-listed-message{--override-ignore-message-background-color:rgb(72 72 0)}.show-more-message > .link{margin-left:5px}.show-more-message{text-align:center;font-style:italic;padding:4px;border-top:1px solid var(--color-details-hairline)}.call-frame-item{padding:3px 8px 3px 20px;position:relative;min-height:18px;line-height:15px;display:flex;flex-wrap:wrap}.call-frame-title-text{text-overflow:ellipsis;overflow:hidden}.async-header + .call-frame-item{border-top:0}.call-frame-item:not(.async-header){border-top:1px solid var(--color-details-hairline)}.call-frame-item-title,\n.call-frame-location{display:flex;white-space:nowrap}.async-header .call-frame-item-title{font-weight:bold;color:var(--color-text-primary);background-color:var(--color-background);margin-left:-5px;padding:0 5px;z-index:1}.call-frame-item:focus-visible,\n.call-frame-item.async-header:focus-visible .call-frame-item-title{background-color:var(--legacy-focus-bg-color)}.ignore-listed-checkbox:focus-visible{outline-width:unset}.call-frame-item:not(.async-header):hover{background-color:var(--color-background-elevation-1)}.call-frame-location{color:var(--color-text-secondary);margin-left:auto;padding:0 10px}.async-header::before{content:" ";width:100%;border-top:1px solid var(--color-details-hairline);margin-top:8px;position:absolute;left:0}.ignore-listed-call-frame{opacity:60%;font-style:italic}.selected-call-frame-icon{display:none;position:absolute;top:3px;left:4px}.call-frame-item.selected .selected-call-frame-icon{display:block}.call-frame-warning-icon{display:block;position:absolute;top:3px;right:4px}@media (forced-colors: active){.call-frame-item:focus-visible,\n  .call-frame-item:not(.async-header):hover{forced-color-adjust:none;background-color:Highlight}.call-frame-item:focus-visible *,\n  .call-frame-item:not(.async-header):hover *{color:HighlightText}}\n/*# sourceURL=callStackSidebarPane.css */\n');const $={callStack:"Call Stack",notPaused:"Not paused",onIgnoreList:"on ignore list",showIgnorelistedFrames:"Show ignore-listed frames",showMore:"Show more",copyStackTrace:"Copy stack trace",callFrameWarnings:"Some call frames have warnings",debugFileNotFound:'Failed to load debug file "{PH1}".',restartFrame:"Restart frame"},K=e.i18n.registerUIStrings("panels/sources/CallStackSidebarPane.ts",$),J=e.i18n.getLocalizedString.bind(void 0,K);let Y;class X extends t.View.SimpleView{ignoreListMessageElement;ignoreListCheckboxElement;notPausedMessageElement;callFrameWarningsElement;items;list;showMoreMessageElement;showIgnoreListed;locationPool;updateThrottler;maxAsyncStackChainDepth;updateItemThrottler;scheduledForUpdateItems;muteActivateItem;lastDebuggerModel=null;constructor(){super(J($.callStack),!0),({element:this.ignoreListMessageElement,checkbox:this.ignoreListCheckboxElement}=this.createIgnoreListMessageElementAndCheckbox()),this.contentElement.appendChild(this.ignoreListMessageElement),this.notPausedMessageElement=this.contentElement.createChild("div","gray-info-message"),this.notPausedMessageElement.textContent=J($.notPaused),this.notPausedMessageElement.tabIndex=-1,this.callFrameWarningsElement=this.contentElement.createChild("div","call-frame-warnings-message");const e=new r.Icon.Icon;e.data={iconName:"warning-filled",color:"var(--icon-warning)",width:"14px",height:"14px"},e.classList.add("call-frame-warning-icon"),this.callFrameWarningsElement.appendChild(e),this.callFrameWarningsElement.appendChild(document.createTextNode(J($.callFrameWarnings))),this.callFrameWarningsElement.tabIndex=-1,this.items=new t.ListModel.ListModel,this.list=new t.ListControl.ListControl(this.items,this,t.ListControl.ListMode.NonViewport),this.contentElement.appendChild(this.list.element),this.list.element.addEventListener("contextmenu",this.onContextMenu.bind(this),!1),self.onInvokeElement(this.list.element,(e=>{const t=this.list.itemForNode(e.target);t&&(this.activateItem(t),e.consume(!0))})),this.showMoreMessageElement=this.createShowMoreMessageElement(),this.showMoreMessageElement.classList.add("hidden"),this.contentElement.appendChild(this.showMoreMessageElement),this.showIgnoreListed=!1,this.locationPool=new d.LiveLocation.LiveLocationPool,this.updateThrottler=new i.Throttler.Throttler(100),this.maxAsyncStackChainDepth=ee,this.update(),this.updateItemThrottler=new i.Throttler.Throttler(100),this.scheduledForUpdateItems=new Set,o.TargetManager.TargetManager.instance().addModelListener(o.DebuggerModel.DebuggerModel,o.DebuggerModel.Events.DebugInfoAttached,this.debugInfoAttached,this)}static instance(e={forceNew:null}){const{forceNew:t}=e;return Y&&!t||(Y=new X),Y}flavorChanged(e){this.showIgnoreListed=!1,this.ignoreListCheckboxElement.checked=!1,this.maxAsyncStackChainDepth=ee,this.update()}debugInfoAttached(){this.update()}setSourceMapSubscription(e){this.lastDebuggerModel!==e&&(this.lastDebuggerModel&&this.lastDebuggerModel.sourceMapManager().removeEventListener(o.SourceMapManager.Events.SourceMapAttached,this.debugInfoAttached,this),this.lastDebuggerModel=e,this.lastDebuggerModel&&this.lastDebuggerModel.sourceMapManager().addEventListener(o.SourceMapManager.Events.SourceMapAttached,this.debugInfoAttached,this))}update(){this.updateThrottler.schedule((()=>this.doUpdate()))}async doUpdate(){this.locationPool.disposeAll(),this.callFrameWarningsElement.classList.add("hidden");const e=t.Context.Context.instance().flavor(o.DebuggerModel.DebuggerPausedDetails);if(this.setSourceMapSubscription(e?.debuggerModel??null),!e)return this.notPausedMessageElement.classList.remove("hidden"),this.ignoreListMessageElement.classList.add("hidden"),this.showMoreMessageElement.classList.add("hidden"),this.items.replaceAll([]),void t.Context.Context.instance().setFlavor(o.DebuggerModel.CallFrame,null);this.notPausedMessageElement.classList.add("hidden");const i=[],n=new Set;for(const t of e.callFrames){const e=oe.createForDebuggerCallFrame(t,this.locationPool,this.refreshItem.bind(this)).then((e=>(Q.set(e,t),e)));i.push(e),t.missingDebugInfoDetails&&n.add(t.missingDebugInfoDetails.details)}const r=await Promise.all(i);n.size&&(this.callFrameWarningsElement.classList.remove("hidden"),t.Tooltip.Tooltip.install(this.callFrameWarningsElement,Array.from(n).join("\n")));let s=e.debuggerModel,a=e.asyncStackTraceId,c=e.asyncStackTrace,l=e.callFrames;for(let{maxAsyncStackChainDepth:e}=this;e>0;--e){if(!c){if(!a)break;if(a.debuggerId){const e=await o.DebuggerModel.DebuggerModel.modelForDebuggerId(a.debuggerId);if(!e)break;s=e}if(c=await s.fetchAsyncStackTrace(a),!c)break}const e=t.UIUtils.asyncStackTraceLabel(c.description,l);r.push(...await oe.createItemsForAsyncStack(e,s,c.callFrames,this.locationPool,this.refreshItem.bind(this))),l=c.callFrames,a=c.parentId,c=c.parent}this.showMoreMessageElement.classList.toggle("hidden",!c),this.items.replaceAll(r);for(const e of this.items)this.refreshItem(e);if(this.maxAsyncStackChainDepth===ee){this.list.selectNextItem(!0,!1);const e=this.list.selectedItem();e&&this.activateItem(e)}this.updatedForTest()}updatedForTest(){}refreshItem(e){this.scheduledForUpdateItems.add(e),this.updateItemThrottler.schedule((async()=>{const e=Array.from(this.scheduledForUpdateItems);if(this.scheduledForUpdateItems.clear(),this.muteActivateItem=!0,!this.showIgnoreListed&&this.items.every((e=>e.isIgnoreListed))){this.showIgnoreListed=!0;for(let e=0;e<this.items.length;++e)this.list.refreshItemByIndex(e);this.ignoreListMessageElement.classList.toggle("hidden",!0)}else{this.showIgnoreListed=this.ignoreListCheckboxElement.checked;const t=new Set(e);let i=!1;for(let e=0;e<this.items.length;++e){const o=this.items.at(e);t.has(o)&&this.list.refreshItemByIndex(e),i=i||o.isIgnoreListed}this.ignoreListMessageElement.classList.toggle("hidden",!i)}delete this.muteActivateItem}))}createElementForItem(e){const i=document.createElement("div");i.classList.add("call-frame-item");const n=i.createChild("div","call-frame-item-title").createChild("div","call-frame-title-text");if(n.textContent=e.title,e.isAsyncHeader)i.classList.add("async-header");else{t.Tooltip.Tooltip.install(n,e.title);const o=i.createChild("div","call-frame-location");o.textContent=c.StringUtilities.trimMiddle(e.linkText,30),t.Tooltip.Tooltip.install(o,e.linkText),i.classList.toggle("ignore-listed-call-frame",e.isIgnoreListed),e.isIgnoreListed&&t.ARIAUtils.setDescription(i,J($.onIgnoreList)),Q.has(e)||t.ARIAUtils.setDisabled(i,!0)}const s=Q.get(e),a=s===t.Context.Context.instance().flavor(o.DebuggerModel.CallFrame);i.classList.toggle("selected",a),t.ARIAUtils.setSelected(i,a),i.classList.toggle("hidden",!this.showIgnoreListed&&e.isIgnoreListed);const l=new r.Icon.Icon;if(l.data={iconName:"large-arrow-right-filled",color:"var(--icon-arrow-main-thread)",width:"14px",height:"14px"},l.classList.add("selected-call-frame-icon"),i.appendChild(l),i.tabIndex=e===this.list.selectedItem()?0:-1,s&&s.missingDebugInfoDetails){const e=new r.Icon.Icon;e.data={iconName:"warning-filled",color:"var(--icon-warning)",width:"14px",height:"14px"},e.classList.add("call-frame-warning-icon");const o=s.missingDebugInfoDetails.resources.map((e=>J($.debugFileNotFound,{PH1:e})));t.Tooltip.Tooltip.install(e,[s.missingDebugInfoDetails.details,...o].join("\n")),i.appendChild(e)}return i}heightForItem(e){return console.assert(!1),0}isItemSelectable(e){return!0}selectedItemChanged(e,t,i,o){i&&(i.tabIndex=-1),o&&(this.setDefaultFocusedElement(o),o.tabIndex=0,this.hasFocus()&&o.focus())}updateSelectedItemARIA(e,t){return!0}createIgnoreListMessageElementAndCheckbox(){const e=document.createElement("div");e.classList.add("ignore-listed-message");const t=e.createChild("label");t.classList.add("ignore-listed-message-label");const i=t.createChild("input");i.tabIndex=0,i.type="checkbox",i.classList.add("ignore-listed-checkbox"),t.append(J($.showIgnorelistedFrames));return i.addEventListener("click",(()=>{this.showIgnoreListed=i.checked;for(const e of this.items)this.refreshItem(e)})),{element:e,checkbox:i}}createShowMoreMessageElement(){const e=document.createElement("div");e.classList.add("show-more-message"),e.createChild("span");const t=e.createChild("span","link");return t.textContent=J($.showMore),t.addEventListener("click",(()=>{this.maxAsyncStackChainDepth+=ee,this.update()}),!1),e}onContextMenu(e){const i=this.list.itemForNode(e.target);if(!i)return;const o=new t.ContextMenu.ContextMenu(e),n=Q.get(i);n&&o.defaultSection().appendItem(J($.restartFrame),(()=>{a.userMetrics.actionTaken(a.UserMetrics.Action.StackFrameRestarted),n.restart()}),!n.canBeRestarted),o.defaultSection().appendItem(J($.copyStackTrace),this.copyStackTrace.bind(this)),i.uiLocation&&this.appendIgnoreListURLContextMenuItems(o,i.uiLocation.uiSourceCode),o.show()}onClick(e){const t=this.list.itemForNode(e.target);t&&this.activateItem(t)}activateItem(e){const n=e.uiLocation;if(this.muteActivateItem||!n)return;this.list.selectItem(e);const r=Q.get(e),s=this.activeCallFrameItem();r&&s!==e?(r.debuggerModel.setSelectedCallFrame(r),t.Context.Context.instance().setFlavor(o.DebuggerModel.CallFrame,r),s&&this.refreshItem(s),this.refreshItem(e)):i.Revealer.reveal(n)}activeCallFrameItem(){const e=t.Context.Context.instance().flavor(o.DebuggerModel.CallFrame);return e&&this.items.find((t=>Q.get(t)===e))||null}appendIgnoreListURLContextMenuItems(e,t){const i=u.Persistence.PersistenceImpl.instance().binding(t);i&&(t=i.network);const o=e.section("ignoreList");if(!(o.items.length>0))for(const{text:e,callback:i}of d.IgnoreListManager.IgnoreListManager.instance().getIgnoreListURLContextMenuItems(t))o.appendItem(e,i)}selectNextCallFrameOnStack(){const e=this.activeCallFrameItem();for(let t=e?this.items.indexOf(e)+1:0;t<this.items.length;t++){const e=this.items.at(t);if(Q.has(e)){this.activateItem(e);break}}}selectPreviousCallFrameOnStack(){const e=this.activeCallFrameItem();for(let t=e?this.items.indexOf(e)-1:this.items.length-1;t>=0;t--){const e=this.items.at(t);if(Q.has(e)){this.activateItem(e);break}}}copyStackTrace(){const e=[];for(const t of this.items){let i=t.title;t.uiLocation&&(i+=" ("+t.uiLocation.linkText(!0)+")"),e.push(i)}a.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(e.join("\n"))}wasShown(){super.wasShown(),this.registerCSSFiles([G])}}const Q=new WeakMap,Z=Symbol("element"),ee=32;let te;class ie{static instance(e={forceNew:null}){const{forceNew:t}=e;return te&&!t||(te=new ie),te}handleAction(e,t){switch(t){case"debugger.next-call-frame":return X.instance().selectNextCallFrameOnStack(),!0;case"debugger.previous-call-frame":return X.instance().selectPreviousCallFrameOnStack(),!0}return!1}}class oe{isIgnoreListed;title;linkText;uiLocation;isAsyncHeader;updateDelegate;static async createForDebuggerCallFrame(e,i,o){const n=e.functionName,r=new oe(t.UIUtils.beautifyFunctionName(n),o);return await d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().createCallFrameLiveLocation(e.location(),r.update.bind(r),i),h.NamesResolver.resolveDebuggerFrameFunctionName(e).then((e=>{e&&e!==n&&(r.title=e,r.updateDelegate(r))})),r}static async createItemsForAsyncStack(e,i,o,n,r){const s=new WeakMap,a=new oe(e,r);s.set(a,new Set),a.isAsyncHeader=!0;const c=[],l=[];for(const e of o){const o=new oe(t.UIUtils.beautifyFunctionName(e.functionName),u),r=i.createRawLocationByScriptId(e.scriptId,e.lineNumber,e.columnNumber);l.push(d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().createCallFrameLiveLocation(r,o.update.bind(o),n)),c.push(o)}return await Promise.all(l),r(a),[a,...c];function u(e){r(e);let t=!1;const i=s.get(a);i&&(e.isIgnoreListed?(i.delete(e),t=0===i.size):(t=0===i.size,i.add(e)),a.isIgnoreListed=0===i.size),t&&r(a)}}constructor(e,t){this.isIgnoreListed=!1,this.title=e,this.linkText="",this.uiLocation=null,this.isAsyncHeader=!1,this.updateDelegate=t}async update(e){const t=await e.uiLocation();this.isIgnoreListed=await e.isIgnoreListed(),this.linkText=t?t.linkText():"",this.uiLocation=t,this.updateDelegate(this)}}var ne=Object.freeze({__proto__:null,CallStackSidebarPane:X,elementSymbol:Z,defaultMaxAsyncStackChainDepth:ee,ActionDelegate:ie,Item:oe});class re{uiSourceCode;constructor(e,t){this.uiSourceCode=e}static accepts(e){return!1}willHide(){}rightToolbarItems(){return[]}leftToolbarItems(){return[]}populateLineGutterContextMenu(e,t){}populateTextAreaContextMenu(e,t,i){}decorationChanged(e,t){}editorExtension(){return[]}editorInitialized(e){}dispose(){}}var se=Object.freeze({__proto__:null,Plugin:re});const ae={clickToShowCoveragePanel:"Click to show Coverage Panel",showDetails:"Show Details",coverageS:"Coverage: {PH1}",coverageNa:"Coverage: n/a"},ce=e.i18n.registerUIStrings("panels/sources/CoveragePlugin.ts",ae),le=e.i18n.getLocalizedString.bind(void 0,ce);class de extends re{originalSourceCode;infoInToolbar;model;coverage;constructor(e){super(e),this.originalSourceCode=this.uiSourceCode,this.infoInToolbar=new t.Toolbar.ToolbarButton(le(ae.clickToShowCoveragePanel)),this.infoInToolbar.setSecondary(),this.infoInToolbar.addEventListener(t.Toolbar.ToolbarButton.Events.Click,(()=>{t.ViewManager.ViewManager.instance().showView("coverage")}));const i=o.TargetManager.TargetManager.instance().primaryPageTarget();i&&(this.model=i.model(g.CoverageModel.CoverageModel),this.model&&(this.model.addEventListener(g.CoverageModel.Events.CoverageReset,this.handleReset,this),this.coverage=this.model.getCoverageForUrl(this.originalSourceCode.url()),this.coverage&&this.coverage.addEventListener(g.CoverageModel.URLCoverageInfo.Events.SizesChanged,this.handleCoverageSizesChanged,this))),this.updateStats()}dispose(){this.coverage&&this.coverage.removeEventListener(g.CoverageModel.URLCoverageInfo.Events.SizesChanged,this.handleCoverageSizesChanged,this),this.model&&this.model.removeEventListener(g.CoverageModel.Events.CoverageReset,this.handleReset,this)}static accepts(e){return e.contentType().isDocumentOrScriptOrStyleSheet()}handleReset(){this.coverage=null,this.updateStats()}handleCoverageSizesChanged(){this.updateStats()}updateStats(){if(this.coverage){this.infoInToolbar.setTitle(le(ae.showDetails));const t=new Intl.NumberFormat(e.DevToolsLocale.DevToolsLocale.instance().locale,{style:"percent",maximumFractionDigits:1});this.infoInToolbar.setText(le(ae.coverageS,{PH1:t.format(this.coverage.usedPercentage())}))}else this.infoInToolbar.setTitle(le(ae.clickToShowCoveragePanel)),this.infoInToolbar.setText(le(ae.coverageNa))}rightToolbarItems(){return[this.infoInToolbar]}editorExtension(){return be.of([])}getCoverageManager(){return this.uiSourceCode.getDecorationData(p.SourceFrame.DecoratorType.COVERAGE)}editorInitialized(e){this.getCoverageManager()&&this.startDecoUpdate(e)}decorationChanged(e,t){e===p.SourceFrame.DecoratorType.COVERAGE&&this.startDecoUpdate(t)}startDecoUpdate(e){const i=this.getCoverageManager();(i?i.usageByLine(this.uiSourceCode):Promise.resolve([])).then((i=>{const o=Boolean(e.state.field(me,!1));var r;i.length?o?e.dispatch({effects:ge.of(i)}):e.dispatch({effects:be.reconfigure([me.init((e=>pe(i,e))),(r=this.uiSourceCode.url(),n.gutter({markers:e=>e.state.field(me),domEventHandlers:{click:()=>(t.ViewManager.ViewManager.instance().showView("coverage").then((()=>{const e=t.ViewManager.ViewManager.instance().view("coverage");return e&&e.widget()})).then((e=>{const t=r.match(/(.*):formatted$/),i=t&&t[1]||r;e.selectCoverageItemByUrl(i)})),!0)},class:"cm-coverageGutter"})),fe])}):o&&e.dispatch({effects:be.reconfigure([])})}))}}const ue=new class extends n.GutterMarker{elementClass="cm-coverageUsed"},he=new class extends n.GutterMarker{elementClass="cm-coverageUnused"};function pe(e,t){const i=new n.RangeSetBuilder;for(let o=0;o<e.length;o++){const n=e[o];if(void 0!==n&&o<t.doc.lines){const e=t.doc.line(o+1).from;i.add(e,e,n?ue:he)}}return i.finish()}const ge=n.StateEffect.define(),me=n.StateField.define({create:()=>n.RangeSet.empty,update:(e,t)=>t.effects.reduce(((e,i)=>i.is(ge)?pe(i.value,t.state):e),e.map(t.changes))});const be=new n.Compartment,fe=n.EditorView.baseTheme({".cm-coverageGutter":{width:"5px",marginLeft:"3px"},".cm-coverageUnused":{backgroundColor:"var(--color-accent-red)"},".cm-coverageUsed":{backgroundColor:"var(--color-coverage-used)"}});var Se=Object.freeze({__proto__:null,CoveragePlugin:de});const ve={openColorPicker:"Open color picker.",openCubicBezierEditor:"Open cubic bezier editor."},Ce=e.i18n.registerUIStrings("panels/sources/CSSPlugin.ts",ve),we=e.i18n.getLocalizedString.bind(void 0,Ce),Ie=new Set(["ColorLiteral","NumberLiteral","StringLiteral","Comment","Important"]);async function xe(e,t,i){const r=n.syntaxTree(e.state).resolveInner(e.pos,-1);if("ClassName"===r.name){l(i);const e=function(e,t){const i=t.getStyleSheetIdsForURL(e);return i.length,i[0]}(t.url(),i),o=await i.getClassNames(e);return{from:r.from,options:o.map((e=>({type:"constant",label:e})))}}const s=function(e,t){if(Ie.has(e.name))return null;for(let i=e;i&&"StyleSheet"!==i.name&&"Styles"!==i.name&&"CallExpression"!==i.name;i=i.parent)if("Declaration"===i.name){const e=i.getChild("PropertyName"),o=i.getChild(":");return e&&o&&o.to<=t?e:null}return null}(r,e.pos);if(s){const t=o.CSSMetadata.cssMetadata().getPropertyValues(e.state.sliceDoc(s.from,s.to));return{from:"ValueName"===r.name?r.from:e.pos,options:t.map((e=>({type:"constant",label:e}))),validFor:/^[\w\P{ASCII}\-]+$/u}}return null}class ye extends n.WidgetType{#i;#o;#n;constructor(e,t,i){super(),this.#o=e,this.#i=t,this.#n=i}eq(e){return this.#o.equal(e.#o)&&this.#i===e.#i&&this.#n===e.#n}toDOM(e){const t=new b.ColorSwatch.ColorSwatch;t.renderColor(this.#o,!1,we(ve.openColorPicker));const i=t.createChild("span");return i.textContent=this.#i,i.setAttribute("hidden","true"),t.addEventListener(b.ColorSwatch.ColorChangedEvent.eventName,(i=>{e.dispatch({changes:{from:this.#n,to:this.#n+this.#i.length,insert:i.data.text}}),this.#i=i.data.text,this.#o=t.getColor()})),t.addEventListener(b.ColorSwatch.ClickEvent.eventName,(i=>{i.consume(!0),e.dispatch({effects:ke.of({type:0,pos:e.posAtDOM(t),text:this.#i,swatch:t,color:this.#o})})})),t}ignoreEvent(){return!0}}class Ee extends n.WidgetType{curve;text;constructor(e,t){super(),this.curve=e,this.text=t}eq(e){return this.curve.asCSSText()===e.curve.asCSSText()&&this.text===e.text}toDOM(e){const i=b.Swatches.BezierSwatch.create();return i.setBezierText(this.text),t.Tooltip.Tooltip.install(i.iconElement(),we(ve.openCubicBezierEditor)),i.iconElement().addEventListener("click",(t=>{t.consume(!0),e.dispatch({effects:ke.of({type:1,pos:e.posAtDOM(i),text:this.text,swatch:i,curve:this.curve})})}),!1),i.hideText(!0),i}ignoreEvent(){return!0}}const ke=n.StateEffect.define(),Te=n.Annotation.define(),Le=n.StateField.define({create:()=>null,update(e,t){!t.docChanged&&!t.selection||t.annotation(Te)||(e=null);for(const i of t.effects)i.is(ke)&&(e=i.value);return e},provide:e=>n.showTooltip.from(e,(e=>e&&function(e){return{pos:e.pos,arrow:!0,create(t){let i,o,n=e.text;if(0===e.type){const n=new m.Spectrum.Spectrum;o=e=>{n.addEventListener(m.Spectrum.Events.ColorChanged,e)},n.addEventListener(m.Spectrum.Events.SizeChanged,(()=>t.requestMeasure())),n.setColor(e.color,e.color.format()),i=n,a.userMetrics.colorPickerOpenedFrom(0)}else{const t=new b.BezierEditor.BezierEditor(e.curve);i=t,o=e=>{t.addEventListener(b.BezierEditor.Events.BezierChanged,e)}}const r=document.createElement("div");return r.className="cm-tooltip-swatchEdit",i.markAsRoot(),i.show(r),i.showWidget(),i.element.addEventListener("keydown",(o=>{"Escape"===o.key&&(o.consume(),t.dispatch({effects:ke.of(null),changes:n===e.text?void 0:{from:e.pos,to:e.pos+n.length,insert:e.text}}),i.hideWidget(),t.focus())})),i.element.addEventListener("focusout",(e=>{e.relatedTarget&&!i.element.contains(e.relatedTarget)&&(t.dispatch({effects:ke.of(null)}),i.hideWidget())}),!1),i.element.addEventListener("mousedown",(e=>e.consume())),{dom:r,resize:!1,offset:{x:-8,y:0},mount:()=>{i.focus(),i.wasShown(),o((i=>{t.dispatch({changes:{from:e.pos,to:e.pos+n.length,insert:i.data},annotations:Te.of(!0)}),n=i.data}))}}}}}(e)))});function Me(e,o,r){const s=new n.RangeSetBuilder;return function(e,o,r,s,a){let c=e.doc.lineAt(o);function l(t,i){return t>=c.to&&(c=e.doc.lineAt(t)),c.text.slice(t-c.from,i-c.from)}const d=n.ensureSyntaxTree(e,r,100);d&&d.iterate({from:o,to:r,enter:o=>{let n;if("ValueName"===o.name||"ColorLiteral"===o.name?n=l(o.from,o.to):"Callee"===o.name&&/^(?:(?:rgba?|hsla?|hwba?|lch|oklch|lab|oklab|color)|cubic-bezier)$/.test(l(o.from,o.to))&&(n=e.sliceDoc(o.from,o.node.parent.to)),n){const e=i.Color.parse(n);if(e)s(o.from,e,n);else{const e=t.Geometry.CubicBezier.parse(n);e&&a(o.from,e,n)}}}})}(e,o,r,((e,t,i)=>{s.add(e,e,n.Decoration.widget({widget:new ye(t,i,e)}))}),((e,t,i)=>{s.add(e,e,n.Decoration.widget({widget:new Ee(t,i)}))})),s.finish()}const Pe=n.ViewPlugin.fromClass(class{decorations;constructor(e){this.decorations=Me(e.state,e.viewport.from,e.viewport.to)}update(e){(e.viewportChanged||e.docChanged)&&(this.decorations=Me(e.state,e.view.viewport.from,e.view.viewport.to))}},{decorations:e=>e.decorations});function Fe(e){if("Unit"===e.name&&(e=e.parent),"NumberLiteral"===e.name){const t=e.lastChild;return{from:e.from,to:t&&"Unit"===t.name?t.from:e.to}}return null}function De(e,t){const{head:i}=e.state.selection.main,o=n.syntaxTree(e.state).resolveInner(i,-1),r=Fe(o)||Fe(o.resolve(i,1));if(!r)return!1;const s=Number(e.state.sliceDoc(r.from,r.to));return!isNaN(s)&&(e.dispatch({changes:{from:r.from,to:r.to,insert:String(s+t)},scrollIntoView:!0,userEvent:"insert.modifyUnit"}),!0)}function Ne(){let e=null;const i=t.ShortcutRegistry.ShortcutRegistry.instance().getShortcutListener({"sources.increment-css":()=>Promise.resolve(De(e,1)),"sources.increment-css-by-ten":()=>Promise.resolve(De(e,10)),"sources.decrement-css":()=>Promise.resolve(De(e,-1)),"sources.decrement-css-by-ten":()=>Promise.resolve(De(e,-10))});return n.EditorView.domEventHandlers({keydown:(t,o)=>{const n=e;return e=o,i(t),e=n,t.defaultPrevented}})}class Ae extends re{#r;constructor(e,t){super(e,t),o.TargetManager.TargetManager.instance().observeModels(o.CSSModel.CSSModel,this)}static accepts(e){return e.contentType().hasStyleSheets()}modelAdded(e){e.target()===o.TargetManager.TargetManager.instance().primaryPageTarget()&&(this.#r=e)}modelRemoved(e){this.#r===e&&(this.#r=void 0)}editorExtension(){return[Ne(),this.#s(),[Pe,Le]]}#s(){const{cssCompletionSource:e}=n.css,t=this.uiSourceCode,i=this.#r;return n.autocompletion({override:[async o=>await xe(o,t,i)||e(o)]})}}var Ue=Object.freeze({__proto__:null,cssBindings:Ne,CSSPlugin:Ae});const Re=new CSSStyleSheet;Re.replaceSync(".paused-status{--override-paused-status-background-color:hsl(50deg 100% 95%);--override-paused-status-color:rgb(107 97 48);padding:6px;border-bottom:1px solid transparent;border-top:1px solid var(--color-details-hairline);background-color:var(--override-paused-status-background-color);color:var(--override-paused-status-color)}.-theme-with-dark-background .paused-status,\n:host-context(.-theme-with-dark-background) .paused-status{--override-paused-status-background-color:hsl(46deg 98% 22%);--override-paused-status-color:#ccc}.paused-status.error-reason{--override-error-reason-background-color:hsl(0deg 100% 97%);--override-error-reason-color:rgb(107 59 59);background-color:var(--override-error-reason-background-color);color:var(--override-error-reason-color)}.-theme-with-dark-background .paused-status.error-reason,\n:host-context(.-theme-with-dark-background) .paused-status.error-reason{--override-error-reason-background-color:rgb(79 0 0);--override-error-reason-color:rgb(196 148 148)}.status-main{font-weight:bold;padding-left:15px;position:relative}.status-sub:not(:empty){padding-left:15px;padding-top:5px;overflow:hidden;text-overflow:ellipsis}.paused-status.error-reason .status-sub{color:var(--color-red);line-height:11px;max-height:27px;user-select:text}devtools-icon{position:absolute;left:-1px;top:-1px}\n/*# sourceURL=debuggerPausedMessage.css */\n");const Be={pausedOnS:"Paused on {PH1}",childSAdded:"Child {PH1} added",descendantSAdded:"Descendant {PH1} added",descendantSRemoved:"Descendant {PH1} removed",pausedOnEventListener:"Paused on event listener",pausedOnXhrOrFetch:"Paused on XHR or fetch",pausedOnException:"Paused on exception",pausedOnPromiseRejection:"Paused on `promise` rejection",pausedOnAssertion:"Paused on assertion",pausedOnDebuggedFunction:"Paused on debugged function",pausedBeforePotentialOutofmemory:"Paused before potential out-of-memory crash",pausedOnCspViolation:"Paused on CSP violation",trustedTypeSinkViolation:"`Trusted Type` Sink Violation",trustedTypePolicyViolation:"`Trusted Type` Policy Violation",pausedOnBreakpoint:"Paused on breakpoint",debuggerPaused:"Debugger paused",subtreeModifications:"subtree modifications",attributeModifications:"attribute modifications",nodeRemoval:"node removal"},Ve=e.i18n.registerUIStrings("panels/sources/DebuggerPausedMessage.ts",Be),Oe=e.i18n.getLocalizedString.bind(void 0,Ve),We=e.i18n.getLazilyComputedLocalizedString.bind(void 0,Ve);class je{elementInternal;contentElement;constructor(){this.elementInternal=document.createElement("div"),this.elementInternal.classList.add("paused-message"),this.elementInternal.classList.add("flex-none");const e=t.Utils.createShadowRootWithCoreStyles(this.elementInternal,{cssFile:[Re],delegatesFocus:void 0});this.contentElement=e.createChild("div"),t.ARIAUtils.markAsPoliteLiveRegion(this.elementInternal,!1)}element(){return this.elementInternal}static descriptionWithoutStack(e){const t=/^\s+at\s/m.exec(e);return t?e.substring(0,t.index-1):e.substring(0,e.lastIndexOf("\n"))}static async createDOMBreakpointHitMessage(t){const n=document.createElement("span"),s=t.debuggerModel.target().model(o.DOMDebuggerModel.DOMDebuggerModel);if(!t.auxData||!s)return n;const a=s.resolveDOMBreakpointData(t.auxData);if(!a)return n;const c=n.createChild("div","status-main"),l=new r.Icon.Icon;l.data={iconName:"info-filled",color:"var(--icon-default)",width:"14px",height:"14px"},c.appendChild(l);const d=He.get(a.type);c.appendChild(document.createTextNode(Oe(Be.pausedOnS,{PH1:d?d():String(null)})));const u=n.createChild("div","status-sub monospace"),h=await i.Linkifier.Linkifier.linkify(a.node);if(u.appendChild(h),a.targetNode){const t=await i.Linkifier.Linkifier.linkify(a.targetNode);let o;o=a.insertion?a.targetNode===a.node?e.i18n.getFormatLocalizedString(Ve,Be.childSAdded,{PH1:t}):e.i18n.getFormatLocalizedString(Ve,Be.descendantSAdded,{PH1:t}):e.i18n.getFormatLocalizedString(Ve,Be.descendantSRemoved,{PH1:t}),u.appendChild(document.createElement("br")),u.appendChild(o)}return n}async render(e,i,n){if(this.contentElement.removeChildren(),this.contentElement.hidden=!e,!e)return;const s=this.contentElement.createChild("div","paused-status"),a="exception"===e.reason||"promiseRejection"===e.reason||"assert"===e.reason||"OOM"===e.reason;let c;if("DOM"===e.reason)c=await je.createDOMBreakpointHitMessage(e);else if("EventListener"===e.reason){let t="";if(e.auxData){const i=o.EventBreakpointsModel.EventBreakpointsManager.instance().resolveEventListenerBreakpointTitle(e.auxData);t=i||o.DOMDebuggerModel.DOMDebuggerManager.instance().resolveEventListenerBreakpointTitle(e.auxData)}c=l(Oe(Be.pausedOnEventListener),t)}else if("XHR"===e.reason){const t=e.auxData;c=l(Oe(Be.pausedOnXhrOrFetch),t.url||"")}else if("exception"===e.reason){const t=e.auxData,i=t.description||t.value||"",o=je.descriptionWithoutStack(i);c=l(Oe(Be.pausedOnException),o,i)}else if("promiseRejection"===e.reason){const t=e.auxData,i=t.description||t.value||"",o=je.descriptionWithoutStack(i);c=l(Oe(Be.pausedOnPromiseRejection),o,i)}else if("assert"===e.reason)c=l(Oe(Be.pausedOnAssertion));else if("debugCommand"===e.reason)c=l(Oe(Be.pausedOnDebuggedFunction));else if("OOM"===e.reason)c=l(Oe(Be.pausedBeforePotentialOutofmemory));else if("CSPViolation"===e.reason&&e.auxData&&e.auxData.violationType){const t=e.auxData.violationType;"trustedtype-sink-violation"===t?c=l(Oe(Be.pausedOnCspViolation),Oe(Be.trustedTypeSinkViolation)):"trustedtype-policy-violation"===t&&(c=l(Oe(Be.pausedOnCspViolation),Oe(Be.trustedTypePolicyViolation)))}else if(e.callFrames.length){const t=await i.rawLocationToUILocation(e.callFrames[0].location()),o=t?n.findBreakpoint(t):null;c=l(Oe(o?Be.pausedOnBreakpoint:Be.debuggerPaused))}else console.warn("ScriptsPanel paused, but callFrames.length is zero.");function l(e,i,o){const n=document.createElement("span"),s=n.createChild("div","status-main"),c=new r.Icon.Icon;if(c.data={iconName:a?"cross-circle-filled":"info-filled",color:a?"var(--icon-error)":"var(--icon-default)",width:"14px",height:"14px"},s.appendChild(c),s.appendChild(document.createTextNode(e)),i){const e=n.createChild("div","status-sub monospace");e.textContent=i,t.Tooltip.Tooltip.install(e,o||i)}return n}s.classList.toggle("error-reason",a),c&&s.appendChild(c)}}const He=new Map([["subtree-modified",We(Be.subtreeModifications)],["attribute-modified",We(Be.attributeModifications)],["node-removed",We(Be.nodeRemoval)]]);var _e=Object.freeze({__proto__:null,DebuggerPausedMessage:je,BreakpointTypeNouns:He});const ze=new CSSStyleSheet;ze.replaceSync('.scripts-debug-toolbar{position:absolute;top:0;width:100%;background-color:var(--color-background-elevation-1);border-bottom:1px solid var(--color-details-hairline);overflow:hidden;z-index:1}.scripts-debug-toolbar-drawer{flex:0 0 52px;transition:margin-top 0.1s ease-in-out;margin-top:-26px;padding-top:25px;background-color:var(--color-background);overflow:hidden;white-space:nowrap}.scripts-debug-toolbar-drawer.expanded{margin-top:0}.scripts-debug-toolbar-drawer > [is="dt-checkbox"]{display:none;padding-left:3px;height:28px}.scripts-debug-toolbar-drawer.expanded > [is="dt-checkbox"]{display:flex}.cursor-auto{cursor:auto}.navigator-tabbed-pane{background-color:var(--color-background-elevation-1)}\n/*# sourceURL=sourcesPanel.css */\n');const qe=new CSSStyleSheet;qe.replaceSync(':host{overflow-y:auto}.icon,\n.icon-basic,\n.icon-badge{margin:-3px -5px}.icon-stack{position:relative;display:inline-flex}.icon-stack > [is="ui-icon"]:not(:first-child){position:absolute;left:0;top:0}.tree-outline{--override-folder-tree-item-color:var(--icon-default);--override-file-tree-item-color:var(--icon-default)}.navigator-fs-tree-item:not(.has-mapped-files):not(.selected) > :not(.selection),\n.navigator-fs-folder-tree-item:not(.has-mapped-files):not(.selected) > :not(.selection){filter:grayscale(50%);opacity:50%}.is-ignore-listed{opacity:50%}.tree-outline li{min-height:20px}.tree-outline li:hover:not(.selected) .selection{display:block;background-color:var(--item-hover-color)}.navigator-file-tree-item.force-white-icons,\n.navigator-folder-tree-item.force-white-icons{--icon-color:var(--icon-force-white)}.navigator-sm-folder-tree-item .icons-container{--override-folder-tree-item-color:var(--icon-folder-authored)}.navigator-fs-folder-tree-item .icons-container{--override-folder-tree-item-color:var(--icon-folder-workspace)}.navigator-fs-tree-item .icons-container{--override-file-tree-item-color:var(--icon-file-authored)}.navigator-nw-folder-tree-item .icons-container{--override-folder-tree-item-color:var(--icon-folder-deployed)}.navigator-sm-script-tree-item .icons-container,\n.navigator-script-tree-item .icons-container,\n.navigator-snippet-tree-item .icons-container{--override-file-tree-item-color:var(--icon-file-script)}.navigator-file-tree-item devtools-icon.dot::before{width:7px;height:7px;top:12px;left:11px}.navigator-file-tree-item.selected:not(.force-white-icons) devtools-icon.dot::before{outline-color:var(--icon-gap-inactive)}.navigator-file-tree-item.selected.force-white-icons devtools-icon.dot::before{background-color:var(--icon-force-white);outline-color:var(--icon-gap-force-white)}.navigator-sm-stylesheet-tree-item .icons-container,\n.navigator-stylesheet-tree-item .icons-container{--override-file-tree-item-color:var(--icon-file-styles)}.navigator-image-tree-item .icons-container,\n.navigator-font-tree-item .icons-container{--override-file-tree-item-color:var(--icon-file-image)}.tree-outline:not(:has(.navigator-deployed-tree-item)) .navigator-sm-folder-tree-item .tree-element-title,\n.tree-outline:not(:has(.navigator-deployed-tree-item)) .navigator-sm-script-tree-item .tree-element-title,\n.tree-outline:not(:has(.navigator-deployed-tree-item)) .navigator-sm-stylesheet-tree-item .tree-element-title{font-style:italic}@media (forced-colors: active){.tree-outline li .leading-icons [is="ui-icon"].icon-mask{background:ButtonText}.tree-outline li:hover:not(.selected) .selection{forced-color-adjust:none;background-color:Highlight}.tree-outline:not(.hide-selection-when-blurred) li.parent:hover:not(.selected)::before,\n  .tree-outline:not(.hide-selection-when-blurred) li:hover:not(.selected) [is="ui-icon"].icon-mask{background-color:HighlightText}.tree-outline li:not(.selected):hover .tree-element-title{forced-color-adjust:none;color:HighlightText}}\n/*# sourceURL=navigatorTree.css */\n');const Ge=new CSSStyleSheet;Ge.replaceSync(".navigator-toolbar{border-bottom:1px solid var(--color-details-hairline);padding-left:8px}\n/*# sourceURL=navigatorView.css */\n");class $e{searchId;searchResultCandidates;searchResultCallback;searchFinishedCallback;searchConfig;constructor(){this.searchId=0,this.searchResultCandidates=[],this.searchResultCallback=null,this.searchFinishedCallback=null,this.searchConfig=null}static filesComparator(e,t){if(e.isDirty()&&!t.isDirty())return-1;if(!e.isDirty()&&t.isDirty())return 1;const i=e.project().type()===v.Workspace.projectTypes.FileSystem&&!u.Persistence.PersistenceImpl.instance().binding(e);if(i!==(t.project().type()===v.Workspace.projectTypes.FileSystem&&!u.Persistence.PersistenceImpl.instance().binding(t)))return i?1:-1;const o=e.url(),n=t.url();return o&&!n?-1:!o&&n?1:c.StringUtilities.naturalOrderComparator(e.fullDisplayName(),t.fullDisplayName())}performIndexing(e){this.stopSearch();const t=this.projects(),o=new i.Progress.CompositeProgress(e);for(let e=0;e<t.length;++e){const i=t[e],n=o.createSubProgress([...i.uiSourceCodes()].length);i.indexContent(n)}}projects(){const e=i.Settings.Settings.instance().moduleSetting("searchInAnonymousAndContentScripts").get();return v.Workspace.WorkspaceImpl.instance().projects().filter((t=>t.type()!==v.Workspace.projectTypes.Service&&(!(!e&&t.isServiceProject()&&t.type()!==v.Workspace.projectTypes.Formatter)&&!(!e&&t.type()===v.Workspace.projectTypes.ContentScripts))))}performSearch(e,t,o,n){this.stopSearch(),this.searchResultCandidates=[],this.searchResultCallback=o,this.searchFinishedCallback=n,this.searchConfig=e;const r=[],s=new i.Progress.CompositeProgress(t),a=s.createSubProgress(),c=new i.Progress.CompositeProgress(s.createSubProgress());for(const t of this.projects()){const i=[...t.uiSourceCodes()].length,o=c.createSubProgress(i),n=this.projectFilesMatchingFileQuery(t,e),s=t.findFilesMatchingSearchRequest(e,n,o).then(this.processMatchingFilesForProject.bind(this,this.searchId,t,e,n));r.push(s)}Promise.all(r).then(this.processMatchingFiles.bind(this,this.searchId,a,this.searchFinishedCallback.bind(this,!0)))}projectFilesMatchingFileQuery(e,t,i){const o=[];for(const n of e.uiSourceCodes()){if(!n.contentType().isTextType())continue;const e=u.Persistence.PersistenceImpl.instance().binding(n);e&&e.network===n||(i&&!n.isDirty()||t.filePathMatchesFileQuery(n.fullDisplayName())&&o.push(n.url()))}return o.sort(c.StringUtilities.naturalOrderComparator),o}processMatchingFilesForProject(e,t,i,o,n){if(e!==this.searchId&&this.searchFinishedCallback)return void this.searchFinishedCallback(!1);n.sort(c.StringUtilities.naturalOrderComparator),n=c.ArrayUtilities.intersectOrdered(n,o,c.StringUtilities.naturalOrderComparator);const r=this.projectFilesMatchingFileQuery(t,i,!0);n=c.ArrayUtilities.mergeOrdered(n,r,c.StringUtilities.naturalOrderComparator);const s=[];for(const e of n){const i=t.uiSourceCodeForURL(e);if(!i)continue;const o=d.DefaultScriptMapping.DefaultScriptMapping.scriptForUISourceCode(i);o&&!o.isAnonymousScript()||s.push(i)}s.sort($e.filesComparator),this.searchResultCandidates=c.ArrayUtilities.mergeOrdered(this.searchResultCandidates,s,$e.filesComparator)}processMatchingFiles(e,t,i){if(e!==this.searchId&&this.searchFinishedCallback)return void this.searchFinishedCallback(!1);const o=this.searchResultCandidates;if(!o.length)return t.done(),void i();t.setTotalWork(o.length);let n=0;let r=0;for(let e=0;e<20&&e<o.length;++e)a.call(this);function s(e){e.isDirty()?l.call(this,e,e.workingCopy()):e.requestContent().then((t=>{l.call(this,e,t.content||"")}))}function a(){if(n>=o.length)return r?void 0:(t.done(),void i());++r;const e=o[n++];window.setTimeout(s.bind(this,e),0)}function l(e,i){function o(e,t){return e.lineNumber-t.lineNumber}t.incrementWorked(1);let n=[];const s=this.searchConfig,l=s.queries();if(null!==i){for(let e=0;e<l.length;++e){const t=S.TextUtils.performSearchInContent(i,l[e],!s.ignoreCase(),s.isRegex());n=c.ArrayUtilities.mergeOrdered(n,t,o)}s.queries().length||(n=[new S.ContentProvider.SearchMatch(0,new S.Text.Text(i).lineAt(0))])}if(n&&this.searchResultCallback){const t=new Ke(e,n);this.searchResultCallback(t)}--r,a.call(this)}}stopSearch(){++this.searchId}}class Ke{uiSourceCode;searchMatches;constructor(e,t){this.uiSourceCode=e,this.searchMatches=t}label(){return this.uiSourceCode.displayName()}description(){return this.uiSourceCode.fullDisplayName()}matchesCount(){return this.searchMatches.length}matchLineContent(e){return this.searchMatches[e].lineContent}matchRevealable(e){const t=this.searchMatches[e];return this.uiSourceCode.uiLocation(t.lineNumber,t.columnNumber)}matchLabel(e){return this.searchMatches[e].lineNumber+1}}var Je=Object.freeze({__proto__:null,SourcesSearchScope:$e,FileBasedSearchResult:Ke});let Ye,Xe;class Qe extends E.SearchView.SearchView{constructor(){super("sources")}static instance(){return Ye||(Ye=new Qe),Ye}static async openSearch(e,i){const o=t.ViewManager.ViewManager.instance().view("sources.search-sources-tab");(await t.ViewManager.ViewManager.instance().resolveLocation("drawer-view")).appendView(o),await t.ViewManager.ViewManager.instance().revealView(o);const n=await o.widget();return n.toggle(e,Boolean(i)),n}createScope(){return new $e}}class Ze{static instance(e={forceNew:null}){const{forceNew:t}=e;return Xe&&!t||(Xe=new Ze),Xe}handleAction(e,t){return this.showSearch(),!0}showSearch(){const e=t.InspectorView.InspectorView.instance().element.window().getSelection();let i="";return e&&e.rangeCount&&(i=e.toString().replace(/\r?\n.*/,"")),Qe.openSearch(i)}}var et=Object.freeze({__proto__:null,SearchSourcesView:Qe,ActionDelegate:Ze});const tt={searchInFolder:"Search in folder",searchInAllFiles:"Search in all files",noDomain:"(no domain)",authored:"Authored",authoredTooltip:"Contains original sources",deployed:"Deployed",deployedTooltip:"Contains final sources the browser sees",areYouSureYouWantToExcludeThis:"Are you sure you want to exclude this folder?",areYouSureYouWantToDeleteThis:"Are you sure you want to delete this file?",rename:"Rename…",makeACopy:"Make a copy…",delete:"Delete",areYouSureYouWantToDeleteAll:"Are you sure you want to delete all overrides contained in this folder?",openFolder:"Open folder",newFile:"New file",excludeFolder:"Exclude folder",removeFolderFromWorkspace:"Remove folder from workspace",areYouSureYouWantToRemoveThis:"Are you sure you want to remove this folder?",deleteAllOverrides:"Delete all overrides",sFromSourceMap:"{PH1} (from source map)",sIgnoreListed:"{PH1} (ignore listed)"},it=e.i18n.registerUIStrings("panels/sources/NavigatorView.ts",tt),ot=e.i18n.getLocalizedString.bind(void 0,it),nt={Authored:"authored",Deployed:"deployed",Domain:"domain",File:"file",FileSystem:"fs",FileSystemFolder:"fs-folder",Frame:"frame",NetworkFolder:"nw-folder",Root:"root",SourceMapFolder:"sm-folder",Worker:"worker"},rt=new Map([[nt.Root,1],[nt.Authored,1],[nt.Deployed,5],[nt.Domain,10],[nt.FileSystemFolder,1],[nt.NetworkFolder,1],[nt.SourceMapFolder,2],[nt.File,10],[nt.Frame,70],[nt.Worker,90],[nt.FileSystem,100]]);class st extends t.Widget.VBox{placeholder;scriptsTree;uiSourceCodeNodes;subfolderNodes;rootNode;frameNodes;authoredNode;deployedNode;navigatorGroupByFolderSetting;navigatorGroupByAuthoredExperiment;workspaceInternal;lastSelectedUISourceCode;groupByFrame;groupByAuthored;groupByDomain;groupByFolder;constructor(e){super(!0),this.placeholder=null,this.scriptsTree=new t.TreeOutline.TreeOutlineInShadow,this.scriptsTree.setComparator(st.treeElementsCompare),this.scriptsTree.setFocusable(!1),this.contentElement.appendChild(this.scriptsTree.element),this.setDefaultFocusedElement(this.scriptsTree.element),this.uiSourceCodeNodes=new c.MapUtilities.Multimap,this.subfolderNodes=new Map,this.rootNode=new ut(this),this.rootNode.populate(),this.frameNodes=new Map,this.contentElement.addEventListener("contextmenu",this.handleContextMenu.bind(this),!1),t.ShortcutRegistry.ShortcutRegistry.instance().addShortcutListener(this.contentElement,{"sources.rename":this.renameShortcut.bind(this)}),this.navigatorGroupByFolderSetting=i.Settings.Settings.instance().moduleSetting("navigatorGroupByFolder"),this.navigatorGroupByFolderSetting.addChangeListener(this.groupingChanged.bind(this)),e&&(this.navigatorGroupByAuthoredExperiment=I.Runtime.ExperimentName.AUTHORED_DEPLOYED_GROUPING),d.IgnoreListManager.IgnoreListManager.instance().addChangeListener(this.ignoreListChanged.bind(this)),this.initGrouping(),u.Persistence.PersistenceImpl.instance().addEventListener(u.Persistence.Events.BindingCreated,this.onBindingChanged,this),u.Persistence.PersistenceImpl.instance().addEventListener(u.Persistence.Events.BindingRemoved,this.onBindingChanged,this),u.NetworkPersistenceManager.NetworkPersistenceManager.instance().addEventListener(u.NetworkPersistenceManager.Events.RequestsForHeaderOverridesFileChanged,this.#a,this),o.TargetManager.TargetManager.instance().addEventListener(o.TargetManager.Events.NameChanged,this.targetNameChanged,this),o.TargetManager.TargetManager.instance().observeTargets(this),this.resetWorkspace(v.Workspace.WorkspaceImpl.instance()),this.workspaceInternal.uiSourceCodes().forEach(this.addUISourceCode.bind(this)),d.NetworkProject.NetworkProjectManager.instance().addEventListener(d.NetworkProject.Events.FrameAttributionAdded,this.frameAttributionAdded,this),d.NetworkProject.NetworkProjectManager.instance().addEventListener(d.NetworkProject.Events.FrameAttributionRemoved,this.frameAttributionRemoved,this)}static treeElementOrder(e){if(at.has(e))return 0;const t=e;let i=rt.get(t.nodeType)||0;if(t.uiSourceCode){const e=t.uiSourceCode.contentType();e.isDocument()?i+=3:e.isScript()?i+=5:e.isStyleSheet()?i+=10:i+=15}return i}static appendSearchItem(e,t){let i=ot(tt.searchInFolder);t&&t.trim()||(t="*",i=ot(tt.searchInAllFiles)),e.viewSection().appendItem(i,(()=>{t&&Qe.openSearch(`file:${t.trim()}`)}))}static treeElementsCompare(e,t){const i=st.treeElementOrder(e),o=st.treeElementOrder(t);return i>o?1:i<o?-1:c.StringUtilities.naturalOrderComparator(e.titleAsText(),t.titleAsText())}setPlaceholder(e){function i(){const t=this.scriptsTree.firstChild();t?e.hideWidget():e.showWidget(),this.scriptsTree.element.classList.toggle("hidden",!t)}console.assert(!this.placeholder,"A placeholder widget was already set"),this.placeholder=e,e.show(this.contentElement,this.contentElement.firstChild),i.call(this),this.scriptsTree.addEventListener(t.TreeOutline.Events.ElementAttached,i.bind(this)),this.scriptsTree.addEventListener(t.TreeOutline.Events.ElementsDetached,i.bind(this))}onBindingChanged(e){const t=e.data;let o=!1;const n=this.uiSourceCodeNodes.get(t.network);for(const e of n)e.updateTitle(),o||=e.uiSourceCode().contentType().isFromSourceMap();const r=this.uiSourceCodeNodes.get(t.fileSystem);for(const e of r)e.updateTitle(),o||=e.uiSourceCode().contentType().isFromSourceMap();const s=u.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.relativePath(t.fileSystem);let a=c.DevToolsPath.EmptyEncodedPathString;for(let e=0;e<s.length-1;++e){a=i.ParsedURL.ParsedURL.concatenate(a,s[e]);const n=this.folderNodeId(t.fileSystem.project(),null,null,t.fileSystem.origin(),o,a),r=this.subfolderNodes.get(n);r&&r.updateTitle(),a=i.ParsedURL.ParsedURL.concatenate(a,"/")}const l=this.rootOrDeployedNode().child(t.fileSystem.project().id());l&&l.updateTitle()}#a(e){const t=e.data,i=this.uiSourceCodeNodes.get(t);for(const e of i)e.updateTitle()}focus(){this.scriptsTree.focus()}appendChild(e,t){this.scriptsTree.setFocusable(!0),e.appendChild(t)}removeChild(e,t){e.removeChild(t),0===this.scriptsTree.rootElement().childCount()&&this.scriptsTree.setFocusable(!1)}resetWorkspace(e){this.workspaceInternal&&(this.workspaceInternal.removeEventListener(v.Workspace.Events.UISourceCodeAdded,this.uiSourceCodeAddedCallback,this),this.workspaceInternal.removeEventListener(v.Workspace.Events.UISourceCodeRemoved,this.uiSourceCodeRemovedCallback,this),this.workspaceInternal.removeEventListener(v.Workspace.Events.ProjectAdded,this.projectAddedCallback,this),this.workspaceInternal.removeEventListener(v.Workspace.Events.ProjectRemoved,this.projectRemovedCallback,this)),this.workspaceInternal=e,this.workspaceInternal.addEventListener(v.Workspace.Events.UISourceCodeAdded,this.uiSourceCodeAddedCallback,this),this.workspaceInternal.addEventListener(v.Workspace.Events.UISourceCodeRemoved,this.uiSourceCodeRemovedCallback,this),this.workspaceInternal.addEventListener(v.Workspace.Events.ProjectAdded,this.projectAddedCallback,this),this.workspaceInternal.addEventListener(v.Workspace.Events.ProjectRemoved,this.projectRemovedCallback,this),this.workspaceInternal.projects().forEach(this.projectAdded.bind(this)),this.computeUniqueFileSystemProjectNames()}projectAddedCallback(e){const t=e.data;this.projectAdded(t),t.type()===v.Workspace.projectTypes.FileSystem&&this.computeUniqueFileSystemProjectNames()}projectRemovedCallback(e){const t=e.data;this.removeProject(t),t.type()===v.Workspace.projectTypes.FileSystem&&this.computeUniqueFileSystemProjectNames()}workspace(){return this.workspaceInternal}acceptProject(e){return!e.isServiceProject()}frameAttributionAdded(e){const{uiSourceCode:t}=e.data;if(!this.acceptsUISourceCode(t))return;const i=e.data.frame;this.addUISourceCodeNode(t,i)}frameAttributionRemoved(e){const{uiSourceCode:t}=e.data;if(!this.acceptsUISourceCode(t))return;const i=e.data.frame,o=Array.from(this.uiSourceCodeNodes.get(t)).find((e=>e.frame()===i));o&&this.removeUISourceCodeNode(o)}acceptsUISourceCode(e){return this.acceptProject(e.project())}addUISourceCode(e){if(I.Runtime.experiments.isEnabled(I.Runtime.ExperimentName.JUST_MY_CODE)&&d.IgnoreListManager.IgnoreListManager.instance().isUserOrSourceMapIgnoreListedUISourceCode(e))return;if(!this.acceptsUISourceCode(e))return;const t=d.NetworkProject.NetworkProject.framesForUISourceCode(e);if(t.length)for(const i of t)this.addUISourceCodeNode(e,i);else this.addUISourceCodeNode(e,null);this.uiSourceCodeAdded(e)}addUISourceCodeNode(e,t){const o=e.contentType().isFromSourceMap();let n;n=e.project().type()===v.Workspace.projectTypes.FileSystem?u.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.relativePath(e).slice(0,-1):i.ParsedURL.ParsedURL.extractPath(e.url()).split("/").slice(1,-1);const r=e.project(),s=d.NetworkProject.NetworkProject.targetForUISourceCode(e),a=this.folderNode(e,r,s,t,e.origin(),n,o),c=new ht(this,e,t),l=a.child(c.id);l&&l instanceof ht?this.uiSourceCodeNodes.set(e,l):(a.appendChild(c),this.uiSourceCodeNodes.set(e,c)),this.selectDefaultTreeNode()}uiSourceCodeAdded(e){}uiSourceCodeAddedCallback(e){const t=e.data;this.addUISourceCode(t)}uiSourceCodeRemovedCallback(e){this.removeUISourceCodes([e.data])}tryAddProject(e){this.projectAdded(e);for(const t of e.uiSourceCodes())this.addUISourceCode(t)}projectAdded(e){const t=this.rootOrDeployedNode();!this.acceptProject(e)||e.type()!==v.Workspace.projectTypes.FileSystem||y.ScriptSnippetFileSystem.isSnippetsProject(e)||t.child(e.id())||(t.appendChild(new gt(this,e,e.id(),nt.FileSystem,e.displayName())),this.selectDefaultTreeNode())}selectDefaultTreeNode(){const e=this.rootNode.children();e.length&&!this.scriptsTree.selectedTreeElement&&e[0].treeNode().select(!0,!1)}computeUniqueFileSystemProjectNames(){const e=this.workspaceInternal.projectsForType(v.Workspace.projectTypes.FileSystem);if(!e.length)return;const t=i.Trie.Trie.newArrayTrie(),o=[];for(const i of e){const e=i.fileSystemPath().split("/").reverse();o.push(e),t.add(e)}const n=this.rootOrDeployedNode();for(let r=0;r<e.length;++r){const s=o[r],a=e[r];t.remove(s);const c=t.longestPrefix(s,!1);t.add(s);const l=s.slice(0,c.length+1),d=i.ParsedURL.ParsedURL.encodedPathToRawPathString(l.reverse().join("/")),u=n.child(a.id());u&&u.setTitle(d)}}removeProject(e){if(this.removeUISourceCodes(e.uiSourceCodes()),e.type()!==v.Workspace.projectTypes.FileSystem)return;const t=this.rootNode.child(e.id());t&&this.rootNode.removeChild(t)}folderNodeId(e,t,i,o,n,r){const s=e.type()===v.Workspace.projectTypes.FileSystem?e.id():"";let a=!t||this.groupByAuthored&&n?"":t.id(),c=this.groupByFrame&&i?i.id:"";return this.groupByAuthored&&(n?(a="Authored",c=""):a="Deployed:"+a),a+":"+s+":"+c+":"+o+":"+r}folderNode(e,t,o,n,r,s,a){if(y.ScriptSnippetFileSystem.isSnippetsUISourceCode(e))return this.rootNode;if(o&&!this.groupByFolder&&!a)return this.domainNode(e,t,o,n,r);const c=i.ParsedURL.ParsedURL.join(s,"/"),l=this.folderNodeId(t,o,n,r,a,c);let d=this.subfolderNodes.get(l);if(d)return d;if(!s.length)return o?this.domainNode(e,t,o,n,r):this.rootOrDeployedNode().child(t.id());const u=this.folderNode(e,t,o,n,r,s.slice(0,-1),a);let h=a?nt.SourceMapFolder:nt.NetworkFolder;t.type()===v.Workspace.projectTypes.FileSystem&&(h=nt.FileSystemFolder);const p=i.ParsedURL.ParsedURL.encodedPathToRawPathString(s[s.length-1]);return d=new pt(this,t,l,h,c,p,r),this.subfolderNodes.set(l,d),u.appendChild(d),d}domainNode(e,t,o,n,r){const s=e.contentType().isFromSourceMap(),a=this.frameNode(t,o,n,s);if(!this.groupByDomain)return a;let c=a.child(r);return c||(c=new gt(this,t,r,nt.Domain,this.computeProjectDisplayName(o,r)),n&&r===i.ParsedURL.ParsedURL.extractOrigin(n.url)&&at.add(c.treeNode()),a.appendChild(c),s&&this.groupByAuthored&&c.treeNode().expand(),c)}frameNode(e,t,i,n){if(!this.groupByFrame||!i||this.groupByAuthored&&n)return this.targetNode(e,t,n);let r=this.frameNodes.get(i);if(r)return r;r=new gt(this,e,t.id()+":"+i.id,nt.Frame,i.displayName()),r.setHoverCallback((function(e){if(e){const e=t.model(o.OverlayModel.OverlayModel);e&&i&&e.highlightFrame(i.id)}else o.OverlayModel.OverlayModel.hideDOMNodeHighlight()})),this.frameNodes.set(i,r);const s=i.parentFrame();return this.frameNode(e,s?s.resourceTreeModel().target():t,s,n).appendChild(r),s||(at.add(r.treeNode()),r.treeNode().expand()),r}targetNode(e,t,i){if(this.groupByAuthored&&i)return this.authoredNode||(this.authoredNode=new gt(this,null,"group:Authored",nt.Authored,ot(tt.authored),ot(tt.authoredTooltip)),this.rootNode.appendChild(this.authoredNode),this.authoredNode.treeNode().expand()),this.authoredNode;const n=this.rootOrDeployedNode();if(t===o.TargetManager.TargetManager.instance().scopeTarget())return n;let r=n.child("target:"+t.id());return r||(r=new gt(this,e,"target:"+t.id(),t.type()===o.Target.Type.Frame?nt.Frame:nt.Worker,t.name()),n.appendChild(r)),r}rootOrDeployedNode(){return this.groupByAuthored?(this.deployedNode||(this.deployedNode=new gt(this,null,"group:Deployed",nt.Deployed,ot(tt.deployed),ot(tt.deployedTooltip)),this.rootNode.appendChild(this.deployedNode)),this.deployedNode):this.rootNode}computeProjectDisplayName(e,t){const n=e.model(o.RuntimeModel.RuntimeModel),r=n?n.executionContexts():[];for(const e of r)if(e.name&&e.origin&&t.startsWith(e.origin))return e.name;if(!t)return ot(tt.noDomain);const s=new i.ParsedURL.ParsedURL(t);return(s.isValid?s.host+(s.port?":"+s.port:""):"")||t}revealUISourceCode(e,t){const i=this.uiSourceCodeNodes.get(e);if(0===i.size)return null;const o=i.values().next().value;return o?(this.scriptsTree.selectedTreeElement&&this.scriptsTree.selectedTreeElement.deselect(),this.lastSelectedUISourceCode=e,o.reveal(t),o):null}sourceSelected(e,t){this.lastSelectedUISourceCode=e,i.Revealer.reveal(e,!t)}#c(e){const t=this.scriptsTree.selectedTreeElement,i=t&&t.node;let o=e;for(;o;){if(o===i)return!0;if(o=o.parent,!(e instanceof gt||e instanceof ct))break}return!1}removeUISourceCodes(e){const t=[];for(const i of e){const e=this.uiSourceCodeNodes.get(i);for(const i of e)this.#c(i)?t.push(i):this.removeUISourceCodeNode(i)}t.forEach(this.removeUISourceCodeNode.bind(this))}removeUISourceCodeNode(e){const t=e.uiSourceCode();this.uiSourceCodeNodes.delete(t,e);const i=t.project(),o=d.NetworkProject.NetworkProject.targetForUISourceCode(t),n=e.frame();let r=e.parent;if(!r)return;r.removeChild(e);let s=r;for(;s&&(r=s.parent,r&&s.isEmpty())&&(r!==this.rootNode&&r!==this.deployedNode||i.type()!==v.Workspace.projectTypes.FileSystem)&&(s instanceof gt||s instanceof pt);){if(s.type===nt.Frame){this.discardFrame(n,Boolean(this.groupByAuthored)&&t.contentType().isFromSourceMap());break}const e=this.folderNodeId(i,o,n,t.origin(),t.contentType().isFromSourceMap(),s instanceof pt&&s.folderPath||c.DevToolsPath.EmptyEncodedPathString);this.subfolderNodes.delete(e),r.removeChild(s),s===this.authoredNode?this.authoredNode=void 0:s===this.deployedNode&&(this.deployedNode=void 0),s=r}}reset(e){for(const e of this.uiSourceCodeNodes.valuesArray())e.dispose();this.scriptsTree.removeChildren(),this.scriptsTree.setFocusable(!1),this.uiSourceCodeNodes.clear(),this.subfolderNodes.clear(),this.frameNodes.clear(),this.rootNode.reset(),this.authoredNode=void 0,this.deployedNode=void 0,e||this.resetWorkspace(v.Workspace.WorkspaceImpl.instance())}handleContextMenu(e){}async renameShortcut(){const e=this.scriptsTree.selectedTreeElement,t=e&&e.node;return!!(t&&t.uiSourceCode()&&t.uiSourceCode().canRename())&&(this.rename(t,!1),!0)}handleContextMenuCreate(e,t,o){if(o){const e=u.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.relativePath(o);e.pop(),t=i.ParsedURL.ParsedURL.join(e,"/")}this.create(e,t,o)}handleContextMenuRename(e){this.rename(e,!1)}async handleContextMenuExclude(e,i){await t.UIUtils.ConfirmDialog.show(ot(tt.areYouSureYouWantToExcludeThis))&&(t.UIUtils.startBatchUpdate(),e.excludeFolder(u.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.completeURL(e,i)),t.UIUtils.endBatchUpdate())}async handleContextMenuDelete(e){await t.UIUtils.ConfirmDialog.show(ot(tt.areYouSureYouWantToDeleteThis))&&e.project().deleteFile(e)}handleFileContextMenu(e,i){const o=i.uiSourceCode(),n=new t.ContextMenu.ContextMenu(e);n.appendApplicableItems(o);const r=o.project();r.type()===v.Workspace.projectTypes.FileSystem&&(n.editSection().appendItem(ot(tt.rename),this.handleContextMenuRename.bind(this,i)),n.editSection().appendItem(ot(tt.makeACopy),this.handleContextMenuCreate.bind(this,r,c.DevToolsPath.EmptyEncodedPathString,o)),n.editSection().appendItem(ot(tt.delete),this.handleContextMenuDelete.bind(this,o))),n.show()}async handleDeleteOverrides(e){await t.UIUtils.ConfirmDialog.show(ot(tt.areYouSureYouWantToDeleteAll))&&this.handleDeleteOverridesHelper(e)}handleDeleteOverridesHelper(e){if(e.children().forEach((e=>{this.handleDeleteOverridesHelper(e)})),e instanceof ht){u.Persistence.PersistenceImpl.instance().binding(e.uiSourceCode())&&e.uiSourceCode().project().deleteFile(e.uiSourceCode())}}handleFolderContextMenu(e,o){const n=o.folderPath||c.DevToolsPath.EmptyEncodedPathString,r=o.project||null,s=new t.ContextMenu.ContextMenu(e);if(st.appendSearchItem(s,n),r){if(r.type()===v.Workspace.projectTypes.FileSystem){const e=i.ParsedURL.ParsedURL.urlToRawPathString(u.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.completeURL(r,n),a.Platform.isWin());s.revealSection().appendItem(ot(tt.openFolder),(()=>a.InspectorFrontendHost.InspectorFrontendHostInstance.showItemInFolder(e))),r.canCreateFile()&&s.defaultSection().appendItem(ot(tt.newFile),(()=>{this.handleContextMenuCreate(r,n,void 0)}))}else if(o.origin&&o.folderPath){const e=i.ParsedURL.ParsedURL.concatenate(o.origin,"/",o.folderPath);for(const{text:t,callback:i}of d.IgnoreListManager.IgnoreListManager.instance().getIgnoreListFolderContextMenuItems(e))s.defaultSection().appendItem(t,i)}r.canExcludeFolder(n)&&s.defaultSection().appendItem(ot(tt.excludeFolder),this.handleContextMenuExclude.bind(this,r,n)),r.type()===v.Workspace.projectTypes.FileSystem&&(s.defaultSection().appendAction("sources.add-folder-to-workspace",void 0,!0),o instanceof gt&&s.defaultSection().appendItem(ot(tt.removeFolderFromWorkspace),(async()=>{await t.UIUtils.ConfirmDialog.show(ot(tt.areYouSureYouWantToRemoveThis))&&r.remove()})),"overrides"===r.fileSystem().type()&&s.defaultSection().appendItem(ot(tt.deleteAllOverrides),this.handleDeleteOverrides.bind(this,o))),s.show()}}rename(e,t){const i=e.uiSourceCode();e.rename(function(o){if(!t)return;o?e.treeElement&&e.treeElement.listItemElement.hasFocus()&&this.sourceSelected(i,!0):i.remove()}.bind(this))}async create(e,t,i){let o="";i&&(o=(await i.requestContent()).content||"");const n=await e.createFile(t,null,o);if(!n)return;this.sourceSelected(n,!1);const r=this.revealUISourceCode(n,!0);r&&this.rename(r,!0)}groupingChanged(){this.reset(!0),this.initGrouping(),this.resetWorkspace(v.Workspace.WorkspaceImpl.instance()),this.workspaceInternal.uiSourceCodes().forEach(this.addUISourceCode.bind(this))}ignoreListChanged(){I.Runtime.experiments.isEnabled(I.Runtime.ExperimentName.JUST_MY_CODE)?this.groupingChanged():this.rootNode.updateTitleRecursive()}initGrouping(){this.groupByFrame=!0,this.groupByDomain=this.navigatorGroupByFolderSetting.get(),this.groupByFolder=this.groupByDomain,this.navigatorGroupByAuthoredExperiment?this.groupByAuthored=I.Runtime.experiments.isEnabled(this.navigatorGroupByAuthoredExperiment):this.groupByAuthored=!1}resetForTest(){this.reset(),this.workspaceInternal.uiSourceCodes().forEach(this.addUISourceCode.bind(this))}discardFrame(e,t){if(t)return;const i=this.frameNodes.get(e);if(i){i.parent&&i.parent.removeChild(i),this.frameNodes.delete(e);for(const i of e.childFrames)this.discardFrame(i,t)}}targetAdded(e){}targetRemoved(e){const t=this.rootOrDeployedNode(),i=t.child("target:"+e.id());i&&t.removeChild(i)}targetNameChanged(e){const t=e.data,i=this.rootOrDeployedNode().child("target:"+t.id());i&&i.setTitle(t.name())}wasShown(){super.wasShown(),this.scriptsTree.registerCSSFiles([qe]),this.registerCSSFiles([Ge])}}const at=new WeakSet;class ct extends t.TreeOutline.TreeElement{nodeType;navigatorView;hoverCallback;node;hovered;isIgnoreListed;constructor(e,i,o,n){super("",!0),this.listItemElement.classList.add("navigator-"+i+"-tree-item","navigator-folder-tree-item"),t.ARIAUtils.setLabel(this.listItemElement,`${o}, ${i}`),this.nodeType=i,this.title=o,this.tooltip=o,this.navigatorView=e,this.hoverCallback=n;let s="folder";i===nt.Domain?s="cloud":i===nt.Frame?s="frame":i===nt.Worker?s="gears":i===nt.Authored?s="code":i===nt.Deployed&&(s="deployed");const a=new r.Icon.Icon,c=new URL(`../../Images/${s}.svg`,import.meta.url).toString();a.data={iconPath:c,color:"var(--override-folder-tree-item-color)",width:"20px",height:"20px"},this.setLeadingIcons([a])}async onpopulate(){this.node.populate()}onattach(){this.collapse(),this.node.onattach(),this.listItemElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!1),this.listItemElement.addEventListener("mousemove",this.mouseMove.bind(this),!1),this.listItemElement.addEventListener("mouseleave",this.mouseLeave.bind(this),!1)}setIgnoreListed(e){this.isIgnoreListed!==e&&(this.isIgnoreListed=e,this.listItemElement.classList.toggle("is-ignore-listed",e),this.updateTooltip())}setNode(e){this.node=e,this.updateTooltip(),t.ARIAUtils.setLabel(this.listItemElement,`${this.title}, ${this.nodeType}`)}updateTooltip(){if(this.node.tooltip)this.tooltip=this.node.tooltip;else{const e=[];let t=this.node;for(;t&&!t.isRoot()&&t.type===this.node.type;)e.push(t.title),t=t.parent;e.reverse();let i=e.join("/");this.isIgnoreListed&&(i=ot(tt.sIgnoreListed,{PH1:i})),this.tooltip=i}}handleContextMenuEvent(e){this.node&&(this.select(),this.navigatorView.handleFolderContextMenu(e,this.node))}mouseMove(e){!this.hovered&&this.hoverCallback&&(this.hovered=!0,this.hoverCallback(!0))}mouseLeave(e){this.hoverCallback&&(this.hovered=!1,this.hoverCallback(!1))}}class lt extends t.TreeOutline.TreeElement{nodeType;node;navigatorView;uiSourceCodeInternal;constructor(e,o,n,r){super("",!1),this.nodeType=nt.File,this.node=r,this.title=n,this.listItemElement.classList.add("navigator-"+o.contentType().name()+"-tree-item","navigator-file-tree-item"),this.tooltip=o.url(),t.ARIAUtils.setLabel(this.listItemElement,`${o.name()}, ${this.nodeType}`),i.EventTarget.fireEvent("source-tree-file-added",o.fullDisplayName()),this.navigatorView=e,this.uiSourceCodeInternal=o,this.updateIcon()}updateIcon(){const e=u.Persistence.PersistenceImpl.instance().binding(this.uiSourceCodeInternal);let i="document",o=[];if(e){y.ScriptSnippetFileSystem.isSnippetsUISourceCode(e.fileSystem)&&(i="snippet");o=u.NetworkPersistenceManager.NetworkPersistenceManager.instance().project()===e.fileSystem.project()?["dot","purple"]:["dot","green"]}else this.uiSourceCodeInternal.url().endsWith(u.NetworkPersistenceManager.HEADERS_FILENAME)&&u.NetworkPersistenceManager.NetworkPersistenceManager.instance().hasMatchingNetworkUISourceCodeForHeaderOverridesFile(this.uiSourceCodeInternal)?o=["dot","purple"]:y.ScriptSnippetFileSystem.isSnippetsUISourceCode(this.uiSourceCodeInternal)&&(i="snippet");const n=new r.Icon.Icon,s=new URL(`../../Images/${i}.svg`,import.meta.url).toString();n.data={iconPath:s,color:"var(--override-file-tree-item-color)",width:"20px",height:"20px"};for(const e of o)n.classList.add(e);e&&t.Tooltip.Tooltip.install(n,u.PersistenceUtils.PersistenceUtils.tooltipForUISourceCode(this.uiSourceCodeInternal)),this.setLeadingIcons([n])}updateAccessibleName(){t.ARIAUtils.setLabel(this.listItemElement,`${this.uiSourceCodeInternal.name()}, ${this.nodeType}`)}get uiSourceCode(){return this.uiSourceCodeInternal}onattach(){this.listItemElement.draggable=!0,this.listItemElement.addEventListener("click",this.onclick.bind(this),!1),this.listItemElement.addEventListener("contextmenu",this.handleContextMenuEvent.bind(this),!1),this.listItemElement.addEventListener("dragstart",this.ondragstart.bind(this),!1)}shouldRenameOnMouseDown(){if(!this.uiSourceCodeInternal.canRename())return!1;if(!this.treeOutline)return!1;return this===this.treeOutline.selectedTreeElement&&this.treeOutline.element.hasFocus()&&!t.UIUtils.isBeingEdited(this.treeOutline.element)}selectOnMouseDown(e){1===e.which&&this.shouldRenameOnMouseDown()?window.setTimeout(function(){this.shouldRenameOnMouseDown()&&this.navigatorView.rename(this.node,!1)}.bind(this),300):super.selectOnMouseDown(e)}ondragstart(e){e.dataTransfer&&(e.dataTransfer.setData("text/plain",this.uiSourceCodeInternal.url()),e.dataTransfer.effectAllowed="copy")}onspace(){return this.navigatorView.sourceSelected(this.uiSourceCode,!0),!0}onclick(e){this.navigatorView.sourceSelected(this.uiSourceCode,!1)}ondblclick(e){const t=1===e.button;return this.navigatorView.sourceSelected(this.uiSourceCode,!t),!1}onenter(){return this.navigatorView.sourceSelected(this.uiSourceCode,!0),!0}ondelete(){return!0}handleContextMenuEvent(e){this.select(),this.navigatorView.handleFileContextMenu(e,this.node)}}class dt{id;navigatorView;type;childrenInternal;populated;isMerged;parent;title;tooltip;constructor(e,t,i,o){this.id=t,this.navigatorView=e,this.type=i,this.childrenInternal=new Map,this.tooltip=o,this.populated=!1,this.isMerged=!1}treeNode(){throw"Not implemented"}dispose(){}updateTitle(){}updateTitleRecursive(){this.updateTitle();for(const e of this.children())e.updateTitleRecursive()}isRoot(){return!1}hasChildren(){return!0}onattach(){}setTitle(e){throw"Not implemented"}populate(){this.isPopulated()||(this.parent&&this.parent.populate(),this.populated=!0,this.wasPopulated())}wasPopulated(){const e=this.children();for(let t=0;t<e.length;++t)this.navigatorView.appendChild(this.treeNode(),e[t].treeNode())}didAddChild(e){this.isPopulated()&&this.navigatorView.appendChild(this.treeNode(),e.treeNode())}willRemoveChild(e){this.isPopulated()&&this.navigatorView.removeChild(this.treeNode(),e.treeNode())}isPopulated(){return this.populated}isEmpty(){return!this.childrenInternal.size}children(){return[...this.childrenInternal.values()]}child(e){return this.childrenInternal.get(e)||null}appendChild(e){this.childrenInternal.set(e.id,e),e.parent=this,this.didAddChild(e)}removeChild(e){this.willRemoveChild(e),this.childrenInternal.delete(e.id),e.parent=null,e.dispose()}reset(){this.childrenInternal.clear()}}class ut extends dt{constructor(e){super(e,"",nt.Root)}isRoot(){return!0}treeNode(){return this.navigatorView.scriptsTree.rootElement()}}class ht extends dt{uiSourceCodeInternal;treeElement;eventListeners;frameInternal;constructor(e,t,i){super(e,"UISourceCode:"+t.canononicalScriptId(),nt.File),this.uiSourceCodeInternal=t,this.treeElement=null,this.eventListeners=[],this.frameInternal=i}frame(){return this.frameInternal}uiSourceCode(){return this.uiSourceCodeInternal}treeNode(){if(this.treeElement)return this.treeElement;this.treeElement=new lt(this.navigatorView,this.uiSourceCodeInternal,"",this),this.updateTitle();const e=this.updateTitle.bind(this,void 0);return this.eventListeners=[this.uiSourceCodeInternal.addEventListener(v.UISourceCode.Events.TitleChanged,e),this.uiSourceCodeInternal.addEventListener(v.UISourceCode.Events.WorkingCopyChanged,e),this.uiSourceCodeInternal.addEventListener(v.UISourceCode.Events.WorkingCopyCommitted,e)],this.treeElement}updateTitle(e){if(!this.treeElement)return;let t=this.uiSourceCodeInternal.displayName();!e&&this.uiSourceCodeInternal.isDirty()&&(t="*"+t),this.treeElement.title=t,this.treeElement.updateIcon();const i=d.IgnoreListManager.IgnoreListManager.instance().isUserOrSourceMapIgnoreListedUISourceCode(this.uiSourceCodeInternal);this.treeElement.listItemElement.classList.toggle("is-ignore-listed",i);let o=this.uiSourceCodeInternal.url();this.uiSourceCodeInternal.contentType().isFromSourceMap()&&(o=ot(tt.sFromSourceMap,{PH1:this.uiSourceCodeInternal.displayName()})),i&&(o=ot(tt.sIgnoreListed,{PH1:o})),this.treeElement.tooltip=o,this.treeElement.updateAccessibleName(),this.parent?.childrenInternal.delete(this.id),this.id="UISourceCode:"+this.uiSourceCodeInternal.canononicalScriptId(),this.parent?.childrenInternal.set(this.id,this)}hasChildren(){return!1}dispose(){i.EventTarget.removeEventListeners(this.eventListeners)}reveal(e){this.parent&&(this.parent.populate(),this.parent.treeNode().expand()),this.treeElement&&(this.treeElement.reveal(!0),e&&this.treeElement.select(!0))}rename(e){if(!this.treeElement)return;if(this.treeElement.listItemElement.focus(),!this.treeElement.treeOutline)return;const i=this.treeElement.treeOutline.element;function o(o){if(!o)return t.UIUtils.markBeingEdited(i,!1),this.updateTitle(),void this.rename(e);if(this.treeElement){const{parent:e}=this.treeElement;e&&(e.removeChild(this.treeElement),e.appendChild(this.treeElement),this.treeElement.select())}n.call(this,!0)}function n(o){t.UIUtils.markBeingEdited(i,!1),this.updateTitle(),e&&e(o)}t.UIUtils.markBeingEdited(i,!0),this.updateTitle(!0),this.treeElement.startEditingTitle(new t.InplaceEditor.Config(function(e,t,i){if(t!==i)return this.treeElement&&(this.treeElement.title=t),void this.uiSourceCodeInternal.rename(t).then(o.bind(this));n.call(this,!0)}.bind(this),n.bind(this,!1)))}}class pt extends dt{project;folderPath;origin;title;treeElement;constructor(e,t,i,o,n,r,s){super(e,i,o),this.project=t,this.folderPath=n,this.title=r,this.origin=s}treeNode(){return this.treeElement||(this.treeElement=this.createTreeElement(this.title,this),this.updateTitle()),this.treeElement}updateTitle(){if(!this.treeElement)return;const e=i.ParsedURL.ParsedURL.concatenate(this.origin,"/",this.folderPath,"/"),t=d.IgnoreListManager.IgnoreListManager.instance().isUserIgnoreListedURL(e);if(this.treeElement.setIgnoreListed(t),!this.project||this.project.type()!==v.Workspace.projectTypes.FileSystem)return;const o=i.ParsedURL.ParsedURL.concatenate(u.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.fileSystemPath(this.project.id()),"/",this.folderPath),n=u.Persistence.PersistenceImpl.instance().filePathHasBindings(o);this.treeElement.listItemElement.classList.toggle("has-mapped-files",n)}createTreeElement(e,t){const i=new ct(this.navigatorView,this.type,e);return i.setNode(t),i}wasPopulated(){this.treeElement&&this.treeElement.node===this&&this.addChildrenRecursive()}addChildrenRecursive(){const e=this.children();for(let t=0;t<e.length;++t){const i=e[t];this.didAddChild(i),i instanceof pt&&i.addChildrenRecursive()}}shouldMerge(e){return this.type!==nt.Domain&&e instanceof pt}didAddChild(e){if(!this.treeElement)return;let t,i=this.children();if(1===i.length&&this.shouldMerge(e))return e.isMerged=!0,this.treeElement.title=this.treeElement.title+"/"+e.title,e.treeElement=this.treeElement,e.updateTitle(),void this.treeElement.setNode(e);if(2===i.length&&(t=i[0]!==e?i[0]:i[1]),t&&t.isMerged){t.isMerged=!1;const e=[];e.push(this);let o=this;for(;o&&o.isMerged;)o=o.parent,o&&e.push(o);e.reverse();const n=e.map((e=>e.title)).join("/"),r=[];o=t;do{r.push(o),i=o.children(),o=1===i.length?i[0]:null}while(o&&o.isMerged);if(!this.isPopulated()){this.treeElement.title=n,this.treeElement.setNode(this);for(let e=0;e<r.length;++e)r[e].treeElement=null,r[e].isMerged=!1;return void this.updateTitle()}const s=this.treeElement,a=this.createTreeElement(n,this);for(let t=0;t<e.length;++t)e[t].treeElement=a,e[t].updateTitle();s.parent&&this.navigatorView.appendChild(s.parent,a),s.setNode(r[r.length-1]),s.title=r.map((e=>e.title)).join("/"),s.parent&&this.navigatorView.removeChild(s.parent,s),this.navigatorView.appendChild(this.treeElement,s),s.expanded&&a.expand(),this.updateTitle()}this.isPopulated()&&this.navigatorView.appendChild(this.treeElement,e.treeNode())}willRemoveChild(e){const t=e;!t.isMerged&&this.isPopulated()&&this.treeElement&&t.treeElement&&this.navigatorView.removeChild(this.treeElement,t.treeElement)}}class gt extends dt{project;title;hoverCallback;treeElement;constructor(e,t,i,o,n,r){super(e,i,o,r),this.project=t,this.title=n,this.populate()}setHoverCallback(e){this.hoverCallback=e}treeNode(){return this.treeElement||(this.treeElement=new ct(this.navigatorView,this.type,this.title,this.hoverCallback),this.treeElement.setNode(this)),this.treeElement}onattach(){this.updateTitle()}updateTitle(){if(!this.treeElement||!this.project||this.project.type()!==v.Workspace.projectTypes.FileSystem)return;const e=u.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.fileSystemPath(this.project.id()),t=this.treeElement.listItemElement.classList.contains("has-mapped-files"),i=u.Persistence.PersistenceImpl.instance().filePathHasBindings(e);t!==i&&(this.treeElement.listItemElement.classList.toggle("has-mapped-files",i),this.treeElement.childrenListElement.hasFocus()||(i?this.treeElement.expand():this.treeElement.collapse()))}setTitle(e){this.title=e,this.treeElement&&(this.treeElement.title=this.title)}}var mt=Object.freeze({__proto__:null,Types:nt,NavigatorView:st,NavigatorFolderTreeElement:ct,NavigatorSourceTreeElement:lt,NavigatorTreeNode:dt,NavigatorRootTreeNode:ut,NavigatorUISourceCodeTreeNode:ht,NavigatorFolderTreeNode:pt,NavigatorGroupTreeNode:gt});const bt=new CSSStyleSheet;bt.replaceSync(".border-container{border-bottom:1px solid var(--color-details-hairline);flex-shrink:0}\n/*# sourceURL=sourcesNavigator.css */\n");const ft={syncChangesInDevtoolsWithThe:"Sync changes in DevTools with the local filesystem",learnMoreAboutWorkspaces:"Learn more about Workspaces",overridePageAssetsWithFilesFromA:"Override page assets with files from a local folder",learnMore:"Learn more",clearConfiguration:"Clear configuration",selectFolderForOverrides:"Select folder for overrides",contentScriptsServedByExtensions:"Content scripts served by extensions appear here",createAndSaveCodeSnippetsFor:"Create and save code snippets for later reuse",newSnippet:"New snippet",createNewSnippet:"Create new snippet",run:"Run",rename:"Rename…",remove:"Remove",saveAs:"Save as..."},St=e.i18n.registerUIStrings("panels/sources/SourcesNavigator.ts",ft),vt=e.i18n.getLocalizedString.bind(void 0,St);let Ct,wt,It,xt,yt,Et;class kt extends st{constructor(){super(!0),o.TargetManager.TargetManager.instance().addEventListener(o.TargetManager.Events.InspectedURLChanged,this.inspectedURLChanged,this),a.userMetrics.panelLoaded("sources","DevTools.Launch.Sources"),o.TargetManager.TargetManager.instance().addScopeChangeListener(this.onScopeChange.bind(this))}wasShown(){this.registerCSSFiles([bt]),super.wasShown()}static instance(e={forceNew:null}){const{forceNew:t}=e;return Ct&&!t||(Ct=new kt),Ct}acceptProject(e){return e.type()===v.Workspace.projectTypes.Network&&o.TargetManager.TargetManager.instance().isInScope(d.NetworkProject.NetworkProject.getTargetForProject(e))}onScopeChange(){for(const e of v.Workspace.WorkspaceImpl.instance().projects())this.acceptProject(e)?this.tryAddProject(e):this.removeProject(e)}inspectedURLChanged(e){const t=o.TargetManager.TargetManager.instance().scopeTarget();if(e.data!==t)return;const i=t&&t.inspectedURL();if(i)for(const e of this.workspace().uiSourceCodes())this.acceptProject(e.project())&&e.url()===i&&this.revealUISourceCode(e,!0)}uiSourceCodeAdded(e){const t=o.TargetManager.TargetManager.instance().scopeTarget(),i=t&&t.inspectedURL();i&&e.url()===i&&this.revealUISourceCode(e,!0)}}class Tt extends st{constructor(){super();const e=new t.EmptyWidget.EmptyWidget("");this.setPlaceholder(e),e.appendParagraph().appendChild(t.Fragment.html` <div>${vt(ft.syncChangesInDevtoolsWithThe)}</div><br> ${t.XLink.XLink.create("https://developer.chrome.com/docs/devtools/workspaces/",vt(ft.learnMoreAboutWorkspaces))} `);const i=new t.Toolbar.Toolbar("navigator-toolbar");i.appendItemsAtLocation("files-navigator-toolbar").then((()=>{i.empty()||this.contentElement.insertBefore(i.element,this.contentElement.firstChild)}))}static instance(){return wt||(wt=new Tt),wt}sourceSelected(e,t){a.userMetrics.actionTaken(a.UserMetrics.Action.FileSystemSourceSelected),super.sourceSelected(e,t)}acceptProject(e){return e.type()===v.Workspace.projectTypes.FileSystem&&"overrides"!==u.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.fileSystemType(e)&&!y.ScriptSnippetFileSystem.isSnippetsProject(e)}handleContextMenu(e){const i=new t.ContextMenu.ContextMenu(e);i.defaultSection().appendAction("sources.add-folder-to-workspace",void 0,!0),i.show()}}class Lt extends st{toolbar;constructor(){super();const e=new t.EmptyWidget.EmptyWidget("");this.setPlaceholder(e),e.appendParagraph().appendChild(t.Fragment.html` <div>${vt(ft.overridePageAssetsWithFilesFromA)}</div><br> ${t.XLink.XLink.create("https://developers.google.com/web/updates/2018/01/devtools#overrides",vt(ft.learnMore))} `),this.toolbar=new t.Toolbar.Toolbar("navigator-toolbar"),this.contentElement.insertBefore(this.toolbar.element,this.contentElement.firstChild),u.NetworkPersistenceManager.NetworkPersistenceManager.instance().addEventListener(u.NetworkPersistenceManager.Events.ProjectChanged,this.updateProjectAndUI,this),this.workspace().addEventListener(v.Workspace.Events.ProjectAdded,this.onProjectAddOrRemoved,this),this.workspace().addEventListener(v.Workspace.Events.ProjectRemoved,this.onProjectAddOrRemoved,this),this.updateProjectAndUI()}static instance(e={forceNew:null}){const{forceNew:t}=e;return It&&!t||(It=new Lt),It}onProjectAddOrRemoved(e){const t=e.data;t&&t.type()===v.Workspace.projectTypes.FileSystem&&"overrides"!==u.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.fileSystemType(t)||this.updateUI()}updateProjectAndUI(){this.reset();const e=u.NetworkPersistenceManager.NetworkPersistenceManager.instance().project();e&&this.tryAddProject(e),this.updateUI()}updateUI(){this.toolbar.removeToolbarItems();const e=u.NetworkPersistenceManager.NetworkPersistenceManager.instance().project();if(e){const o=new t.Toolbar.ToolbarSettingCheckbox(i.Settings.Settings.instance().moduleSetting("persistenceNetworkOverridesEnabled"));this.toolbar.appendToolbarItem(o),this.toolbar.appendToolbarItem(new t.Toolbar.ToolbarSeparator(!0));const n=new t.Toolbar.ToolbarButton(vt(ft.clearConfiguration),"clear");return n.addEventListener(t.Toolbar.ToolbarButton.Events.Click,(()=>{e.remove()})),void this.toolbar.appendToolbarItem(n)}const o=vt(ft.selectFolderForOverrides),n=new t.Toolbar.ToolbarButton(o,"plus",o);n.addEventListener(t.Toolbar.ToolbarButton.Events.Click,(e=>{this.setupNewWorkspace()}),this),this.toolbar.appendToolbarItem(n)}async setupNewWorkspace(){await u.IsolatedFileSystemManager.IsolatedFileSystemManager.instance().addFileSystem("overrides")&&i.Settings.Settings.instance().moduleSetting("persistenceNetworkOverridesEnabled").set(!0)}sourceSelected(e,t){a.userMetrics.actionTaken(a.UserMetrics.Action.OverridesSourceSelected),super.sourceSelected(e,t)}acceptProject(e){return e===u.NetworkPersistenceManager.NetworkPersistenceManager.instance().project()}}class Mt extends st{constructor(){super();const e=new t.EmptyWidget.EmptyWidget("");this.setPlaceholder(e),e.appendParagraph().appendChild(t.Fragment.html` <div>${vt(ft.contentScriptsServedByExtensions)}</div><br> ${t.XLink.XLink.create("https://developer.chrome.com/extensions/content_scripts",vt(ft.learnMore))} `)}static instance(e={forceNew:null}){const{forceNew:t}=e;return xt&&!t||(xt=new Mt),xt}acceptProject(e){return e.type()===v.Workspace.projectTypes.ContentScripts}}class Pt extends st{constructor(){super();const e=new t.EmptyWidget.EmptyWidget("");this.setPlaceholder(e),e.appendParagraph().appendChild(t.Fragment.html` <div>${vt(ft.createAndSaveCodeSnippetsFor)}</div><br> ${t.XLink.XLink.create("https://developer.chrome.com/docs/devtools/javascript/snippets/",vt(ft.learnMore))} `);const i=new t.Toolbar.Toolbar("navigator-toolbar"),o=new t.Toolbar.ToolbarButton(vt(ft.newSnippet),"plus",vt(ft.newSnippet));o.addEventListener(t.Toolbar.ToolbarButton.Events.Click,(e=>{this.create(y.ScriptSnippetFileSystem.findSnippetsProject(),"")})),i.appendToolbarItem(o),this.contentElement.insertBefore(i.element,this.contentElement.firstChild)}static instance(){return yt||(yt=new Pt),yt}acceptProject(e){return y.ScriptSnippetFileSystem.isSnippetsProject(e)}handleContextMenu(e){const i=new t.ContextMenu.ContextMenu(e);i.headerSection().appendItem(vt(ft.createNewSnippet),(()=>this.create(y.ScriptSnippetFileSystem.findSnippetsProject(),""))),i.show()}handleFileContextMenu(e,i){const o=i.uiSourceCode(),n=new t.ContextMenu.ContextMenu(e);n.headerSection().appendItem(vt(ft.run),(()=>y.ScriptSnippetFileSystem.evaluateScriptSnippet(o))),n.editSection().appendItem(vt(ft.rename),(()=>this.rename(i,!1))),n.editSection().appendItem(vt(ft.remove),(()=>o.project().deleteFile(o))),n.saveSection().appendItem(vt(ft.saveAs),this.handleSaveAs.bind(this,o)),n.show()}async handleSaveAs(e){e.commitWorkingCopy();const{content:t}=await e.requestContent();v.FileManager.FileManager.instance().save(this.addJSExtension(e.url()),t||"",!0),v.FileManager.FileManager.instance().close(e.url())}addJSExtension(e){return i.ParsedURL.ParsedURL.concatenate(e,".js")}}class Ft{static instance(e={forceNew:null}){const{forceNew:t}=e;return Et&&!t||(Et=new Ft),Et}handleAction(e,t){switch(t){case"sources.create-snippet":return y.ScriptSnippetFileSystem.findSnippetsProject().createFile(c.DevToolsPath.EmptyEncodedPathString,null,"").then((e=>i.Revealer.reveal(e))),!0;case"sources.add-folder-to-workspace":return u.IsolatedFileSystemManager.IsolatedFileSystemManager.instance().addFileSystem(),!0}return!1}}var Dt=Object.freeze({__proto__:null,NetworkNavigatorView:kt,FilesNavigatorView:Tt,OverridesNavigatorView:Lt,ContentScriptsNavigatorView:Mt,SnippetsNavigatorView:Pt,ActionDelegate:Ft});class Nt{sourcesView;entries=[];current=-1;revealing=!1;constructor(e){this.sourcesView=e}trackSourceFrameCursorJumps(e){e.addEventListener("EditorUpdate",(t=>this.onEditorUpdate(t.data,e)))}onEditorUpdate(e,t){e.docChanged&&this.mapEntriesFor(t.uiSourceCode(),e.changes);const i=e.startState.selection.main,o=e.state.selection.main;!this.revealing&&i.anchor!==o.anchor&&e.transactions.some((e=>Boolean(e.isUserEvent("select.pointer")||e.isUserEvent("select.reveal")||e.isUserEvent("select.search"))))&&(this.updateCurrentState(t.uiSourceCode(),i.head),this.entries.length>this.current+1&&(this.entries.length=this.current+1),this.entries.push(new At(t.uiSourceCode(),o.head)),this.current++,this.entries.length>20&&(this.entries.shift(),this.current--))}updateCurrentState(e,t){if(!this.revealing){const i=this.current>=0?this.entries[this.current]:null;i?.matches(e)&&(i.position=t)}}mapEntriesFor(e,t){for(const i of this.entries)i.matches(e)&&(i.position=t.mapPos(i.position))}reveal(e){const t=v.Workspace.WorkspaceImpl.instance().uiSourceCode(e.projectId,e.url);t&&(this.revealing=!0,this.sourcesView.showSourceLocation(t,e.position,!1,!0),this.revealing=!1)}rollback(){this.current>0&&(this.current--,this.reveal(this.entries[this.current]))}rollover(){this.current<this.entries.length-1&&(this.current++,this.reveal(this.entries[this.current]))}removeHistoryForSourceCode(e){for(let t=this.entries.length-1;t>=0;t--)this.entries[t].matches(e)&&(this.entries.splice(t,1),this.current>=t&&this.current--)}}class At{projectId;url;position;constructor(e,t){this.projectId=e.project().id(),this.url=e.url(),this.position=t}matches(e){return this.url===e.url()&&this.projectId===e.project().id()}}var Ut=Object.freeze({__proto__:null,HistoryDepth:20,EditingLocationHistoryManager:Nt});const Rt=new CSSStyleSheet;Rt.replaceSync("#sources-panel-sources-view{--override-highlight-animation-10pc-background-color:rgb(158 54 153);--override-highlight-animation-10pc-foreground-color:rgb(255 255 255);flex:auto;position:relative}#sources-panel-sources-view .sources-toolbar{display:flex;flex:0 0 27px;background-color:var(--color-background-elevation-1);border-top:var(--legacy-divider-border);overflow:hidden;z-index:0}.sources-toolbar .toolbar{cursor:default}.source-frame-debugger-script{--override-debugger-background-tint:rgb(255 255 194/50%);background-color:var(--override-debugger-background-tint)}.-theme-with-dark-background .source-frame-debugger-script{--override-debugger-background-tint:rgb(61 61 0/50%)}\n/*# sourceURL=sourcesView.css */\n");const Bt=["application/javascript","application/json","application/manifest+json","text/css","text/html","text/javascript","text/x-scss"],Vt={ms:"ms",mb:"MB",kb:"kB"},Ot=e.i18n.registerUIStrings("panels/sources/ProfilePlugin.ts",Vt),Wt=e.i18n.getLocalizedString.bind(void 0,Ot);class jt extends n.GutterMarker{value;constructor(e){super(),this.value=e}eq(e){return this.value===e.value}toDOM(){const e=document.createElement("div");e.className="cm-profileMarker";let t=this.value;const i=c.NumberUtilities.clamp(Math.log10(1+.002*t)/5,.02,1);let o,n;e.style.backgroundColor=`hsla(217, 100%, 70%, ${i.toFixed(3)})`,t/=1e3,t>=1e3?(o=Wt(Vt.mb),t/=1e3,n=t>=20?0:1):(o=Wt(Vt.kb),n=0),e.textContent=t.toFixed(n);const r=e.appendChild(document.createElement("span"));return r.className="cm-units",r.textContent=o,e}}class Ht extends n.GutterMarker{value;constructor(e){super(),this.value=e}eq(e){return this.value===e.value}toDOM(){const e=document.createElement("div");e.className="cm-profileMarker";const t=c.NumberUtilities.clamp(Math.log10(1+10*this.value)/5,.02,1);e.textContent=this.value.toFixed(1),e.style.backgroundColor=`hsla(44, 100%, 50%, ${t.toFixed(3)})`;const i=document.createElement("span");return i.className="cm-units",i.textContent=Wt(Vt.ms),e.appendChild(i),e}}function _t(e,t,i){const o=i===p.SourceFrame.DecoratorType.PERFORMANCE?Ht:jt,r=[];for(const[i,n]of e)if(i<=t.doc.lines){const{from:e}=t.doc.line(i);r.push(new o(n).range(e))}return n.RangeSet.of(r,!0)}const zt=e=>class extends re{updateEffect=n.StateEffect.define();field;gutter;compartment=new n.Compartment;constructor(t){super(t),this.field=n.StateField.define({create:()=>n.RangeSet.empty,update:(t,i)=>i.effects.reduce(((t,o)=>o.is(this.updateEffect)?_t(o.value,i.state,e):t),t.map(i.changes))}),this.gutter=n.gutter({markers:e=>e.state.field(this.field),class:`cm-${e}Gutter`})}static accepts(e){return e.contentType().hasScripts()}getLineMap(){return this.uiSourceCode.getDecorationData(e)}editorExtension(){const t=this.getLineMap();return this.compartment.of(t?[this.field.init((i=>_t(t,i,e))),this.gutter,qt]:[])}decorationChanged(e,t){const i=Boolean(t.state.field(this.field,!1)),o=this.getLineMap();o?i?t.dispatch({effects:this.updateEffect.of(o)}):t.dispatch({effects:this.compartment.reconfigure([this.field.init((t=>_t(o,t,e))),this.gutter,qt])}):i&&t.dispatch({effects:this.compartment.reconfigure([])})}},qt=n.EditorView.baseTheme({".cm-performanceGutter":{width:"60px",backgroundColor:"var(--color-background)",marginLeft:"3px"},".cm-memoryGutter":{width:"48px",backgroundColor:"var(--color-background)",marginLeft:"3px"},".cm-profileMarker":{textAlign:"right",paddingRight:"3px"},".cm-profileMarker .cm-units":{color:"var(--color-text-secondary)",fontSize:"75%",marginLeft:"3px"}}),Gt=zt(p.SourceFrame.DecoratorType.MEMORY),$t=zt(p.SourceFrame.DecoratorType.PERFORMANCE),Kt={fromS:"(From {PH1})",sourceMappedFromS:"(Source mapped from {PH1})"},Jt=e.i18n.registerUIStrings("panels/sources/ResourceOriginPlugin.ts",Kt),Yt=e.i18n.getLocalizedString.bind(void 0,Jt);class Xt extends re{static accepts(e){const t=e.contentType();return t.hasScripts()||t.isFromSourceMap()}rightToolbarItems(){const i=d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance();if(this.uiSourceCode.contentType().isFromSourceMap()){const o=[];for(const e of i.scriptsForUISourceCode(this.uiSourceCode)){const t=i.uiSourceCodeForScript(e);if(!t)continue;const n=t.url(),r=d.ResourceUtils.displayNameForURL(n),s=Yt(Kt.sourceMappedFromS,{PH1:r});o.push(M.Linkifier.Linkifier.linkifyRevealable(t,r,n,s))}for(const e of d.SASSSourceMapping.SASSSourceMapping.uiSourceOrigin(this.uiSourceCode))o.push(M.Linkifier.Linkifier.linkifyURL(e));if(0===o.length)return[];const n=document.createElement("span");return o.forEach(((e,t)=>{t>0&&n.append(", "),n.append(e)})),[new t.Toolbar.ToolbarItem(e.i18n.getFormatLocalizedString(Jt,Kt.fromS,{PH1:n}))]}for(const o of i.scriptsForUISourceCode(this.uiSourceCode))if(o.originStackTrace){const i=Qt.linkifyStackTraceTopFrame(o.debuggerModel.target(),o.originStackTrace);return[new t.Toolbar.ToolbarItem(e.i18n.getFormatLocalizedString(Jt,Kt.fromS,{PH1:i}))]}return[]}}const Qt=new M.Linkifier.Linkifier;var Zt=Object.freeze({__proto__:null,ResourceOriginPlugin:Xt,linkifier:Qt});const ei={enter:"⌘+Enter",ctrlenter:"Ctrl+Enter"},ti=e.i18n.registerUIStrings("panels/sources/SnippetsPlugin.ts",ei),ii=e.i18n.getLocalizedString.bind(void 0,ti);class oi extends re{static accepts(e){return y.ScriptSnippetFileSystem.isSnippetsUISourceCode(e)}rightToolbarItems(){const e=t.Toolbar.Toolbar.createActionButtonForId("debugger.run-snippet");return e.setText(a.Platform.isMac()?ii(ei.enter):ii(ei.ctrlenter)),[e]}editorExtension(){return s.JavaScript.completion()}}var ni,ri=Object.freeze({__proto__:null,SnippetsPlugin:oi});class si extends(i.ObjectWrapper.eventMixin(p.SourceFrame.SourceFrameImpl)){uiSourceCodeInternal;muteSourceCodeEvents;persistenceBinding;uiSourceCodeEventListeners;messageAndDecorationListeners;boundOnBindingChanged;plugins=[];errorPopoverHelper;#l=!1;constructor(e){super((()=>this.workingCopy())),this.uiSourceCodeInternal=e,this.muteSourceCodeEvents=!1,this.persistenceBinding=u.Persistence.PersistenceImpl.instance().binding(e),this.uiSourceCodeEventListeners=[],this.messageAndDecorationListeners=[],this.boundOnBindingChanged=this.onBindingChanged.bind(this),i.Settings.Settings.instance().moduleSetting("persistenceNetworkOverridesEnabled").addChangeListener(this.onNetworkPersistenceChanged,this),this.errorPopoverHelper=new t.PopoverHelper.PopoverHelper(this.textEditor.editor.contentDOM,this.getErrorPopoverContent.bind(this)),this.errorPopoverHelper.setHasPadding(!0),this.errorPopoverHelper.setTimeout(100,100),this.initializeUISourceCode()}async workingCopy(){return this.uiSourceCodeInternal.isDirty()?{content:this.uiSourceCodeInternal.workingCopy(),isEncoded:!1}:this.uiSourceCodeInternal.requestContent()}editorConfiguration(e){return[super.editorConfiguration(e),(t=this.allMessages(),[fi.init((e=>bi.create(hi.create(t),e.doc))),vi]),li.of(this.plugins.map((e=>e.editorExtension())))];var t}onFocus(){super.onFocus(),t.Context.Context.instance().setFlavor(si,this)}onBlur(){super.onBlur(),t.Context.Context.instance().setFlavor(si,null)}installMessageAndDecorationListeners(){if(this.persistenceBinding){const e=this.persistenceBinding.network,t=this.persistenceBinding.fileSystem;this.messageAndDecorationListeners=[e.addEventListener(v.UISourceCode.Events.MessageAdded,this.onMessageAdded,this),e.addEventListener(v.UISourceCode.Events.MessageRemoved,this.onMessageRemoved,this),e.addEventListener(v.UISourceCode.Events.DecorationChanged,this.onDecorationChanged,this),t.addEventListener(v.UISourceCode.Events.MessageAdded,this.onMessageAdded,this),t.addEventListener(v.UISourceCode.Events.MessageRemoved,this.onMessageRemoved,this)]}else this.messageAndDecorationListeners=[this.uiSourceCodeInternal.addEventListener(v.UISourceCode.Events.MessageAdded,this.onMessageAdded,this),this.uiSourceCodeInternal.addEventListener(v.UISourceCode.Events.MessageRemoved,this.onMessageRemoved,this),this.uiSourceCodeInternal.addEventListener(v.UISourceCode.Events.DecorationChanged,this.onDecorationChanged,this)]}uiSourceCode(){return this.uiSourceCodeInternal}setUISourceCode(e){const t=e.contentLoaded()?Promise.resolve():e.requestContent(),i=this.uiSourceCodeInternal;t.then((async()=>{this.uiSourceCodeInternal===i&&(this.unloadUISourceCode(),this.uiSourceCodeInternal=e,e.workingCopy()!==this.textEditor.state.doc.toString()?await this.setDeferredContent(Promise.resolve(e.workingCopyContent())):this.reloadPlugins(),this.initializeUISourceCode())}),console.error)}unloadUISourceCode(){i.EventTarget.removeEventListeners(this.messageAndDecorationListeners),i.EventTarget.removeEventListeners(this.uiSourceCodeEventListeners),this.uiSourceCodeInternal.removeWorkingCopyGetter(),u.Persistence.PersistenceImpl.instance().unsubscribeFromBindingEvent(this.uiSourceCodeInternal,this.boundOnBindingChanged)}initializeUISourceCode(){this.uiSourceCodeEventListeners=[this.uiSourceCodeInternal.addEventListener(v.UISourceCode.Events.WorkingCopyChanged,this.onWorkingCopyChanged,this),this.uiSourceCodeInternal.addEventListener(v.UISourceCode.Events.WorkingCopyCommitted,this.onWorkingCopyCommitted,this),this.uiSourceCodeInternal.addEventListener(v.UISourceCode.Events.TitleChanged,this.onTitleChanged,this)],u.Persistence.PersistenceImpl.instance().subscribeForBindingEvent(this.uiSourceCodeInternal,this.boundOnBindingChanged),this.installMessageAndDecorationListeners(),this.updateStyle();const e=Bt.includes(this.contentType)&&!this.uiSourceCodeInternal.project().canSetFileContent()&&null===u.Persistence.PersistenceImpl.instance().binding(this.uiSourceCodeInternal),t=I.Runtime.experiments.isEnabled("sourcesPrettyPrint")&&!this.uiSourceCodeInternal.contentType().isFromSourceMap();this.setCanPrettyPrint(e,t)}wasShown(){super.wasShown(),this.setEditable(this.canEditSourceInternal())}willHide(){for(const e of this.plugins)e.willHide();super.willHide(),t.Context.Context.instance().setFlavor(si,null),this.uiSourceCodeInternal.removeWorkingCopyGetter()}getContentType(){const e=u.Persistence.PersistenceImpl.instance().binding(this.uiSourceCodeInternal);return e?e.network.mimeType():this.uiSourceCodeInternal.mimeType()}canEditSourceInternal(){return!this.hasLoadError()&&(!this.uiSourceCodeInternal.editDisabled()&&("application/wasm"!==this.uiSourceCodeInternal.mimeType()&&(!!u.Persistence.PersistenceImpl.instance().binding(this.uiSourceCodeInternal)||(!!this.uiSourceCodeInternal.project().canSetFileContent()||!this.uiSourceCodeInternal.project().isServiceProject()&&(!(this.uiSourceCodeInternal.project().type()!==v.Workspace.projectTypes.Network||!u.NetworkPersistenceManager.NetworkPersistenceManager.instance().active())||(!this.pretty||!this.uiSourceCodeInternal.contentType().hasScripts())&&this.uiSourceCodeInternal.contentType()!==i.ResourceType.resourceTypes.Document)))))}onNetworkPersistenceChanged(){this.setEditable(this.canEditSourceInternal())}commitEditing(){this.uiSourceCodeInternal.isDirty()&&(this.muteSourceCodeEvents=!0,this.uiSourceCodeInternal.commitWorkingCopy(),this.muteSourceCodeEvents=!1)}async setContent(e){this.disposePlugins(),this.loadPlugins(),await super.setContent(e);for(const e of this.plugins)e.editorInitialized(this.textEditor);this.#d(),i.EventTarget.fireEvent("source-file-loaded",this.uiSourceCodeInternal.displayName(!0))}createMessage(e){const{lineNumber:t,columnNumber:i}=this.uiLocationToEditorLocation(e.lineNumber(),e.columnNumber());return new di(e,t,i)}allMessages(){return(null!==this.persistenceBinding?[...this.persistenceBinding.network.messages(),...this.persistenceBinding.fileSystem.messages()]:[...this.uiSourceCodeInternal.messages()]).map((e=>this.createMessage(e)))}onTextChanged(){const e=this.pretty;super.onTextChanged(),this.errorPopoverHelper.hidePopover(),ao.instance().updateLastModificationTime(),this.muteSourceCodeEvents=!0,this.isClean()?this.uiSourceCodeInternal.resetWorkingCopy():this.uiSourceCodeInternal.setWorkingCopyGetter((()=>this.textEditor.state.sliceDoc())),this.muteSourceCodeEvents=!1,e!==this.pretty&&(this.updateStyle(),this.reloadPlugins())}onWorkingCopyChanged(){this.muteSourceCodeEvents||this.maybeSetContent(this.uiSourceCodeInternal.workingCopyContent())}onWorkingCopyCommitted(){this.muteSourceCodeEvents||this.maybeSetContent(this.uiSourceCode().workingCopyContent()),this.contentCommitted(),this.updateStyle()}reloadPlugins(){this.disposePlugins(),this.loadPlugins();const e=this.textEditor;e.dispatch({effects:li.reconfigure(this.plugins.map((e=>e.editorExtension())))});for(const t of this.plugins)t.editorInitialized(e)}onTitleChanged(){this.updateLanguageMode("").then((()=>this.reloadPlugins()),console.error)}loadPlugins(){const e=u.Persistence.PersistenceImpl.instance().binding(this.uiSourceCodeInternal),t=e?e.network:this.uiSourceCodeInternal;for(const e of[Ae,Do,oi,Xt,de,Gt,$t])e.accepts(t)&&this.plugins.push(new e(t,this));this.dispatchEventToListeners(ni.ToolbarItemsChanged)}disposePlugins(){for(const e of this.plugins)e.dispose();this.plugins=[]}onBindingChanged(){const e=u.Persistence.PersistenceImpl.instance().binding(this.uiSourceCodeInternal);e!==this.persistenceBinding&&(this.unloadUISourceCode(),this.persistenceBinding=e,this.initializeUISourceCode(),this.reloadMessages(),this.reloadPlugins())}reloadMessages(){const e=this.allMessages(),{editor:t}=this.textEditor;t.dispatch({effects:pi.of(hi.create(e))})}updateStyle(){this.setEditable(this.canEditSourceInternal())}maybeSetContent(e){this.textEditor.state.doc.toString()!==e.content&&this.setDeferredContent(Promise.resolve(e))}populateTextAreaContextMenu(e,t,i){super.populateTextAreaContextMenu(e,t,i),e.appendApplicableItems(this.uiSourceCodeInternal);const o=this.editorLocationToUILocation(t,i);e.appendApplicableItems(new v.UISourceCode.UILocation(this.uiSourceCodeInternal,o.lineNumber,o.columnNumber));for(const o of this.plugins)o.populateTextAreaContextMenu(e,t,i)}populateLineGutterContextMenu(e,t){super.populateLineGutterContextMenu(e,t);for(const i of this.plugins)i.populateLineGutterContextMenu(e,t)}dispose(){this.errorPopoverHelper.dispose(),this.disposePlugins(),this.unloadUISourceCode(),this.textEditor.editor.destroy(),this.detach(),i.Settings.Settings.instance().moduleSetting("persistenceNetworkOverridesEnabled").removeChangeListener(this.onNetworkPersistenceChanged,this)}onMessageAdded(e){const{editor:t}=this.textEditor,i=t.state.field(fi,!1);if(i){const o=this.createMessage(e.data);t.dispatch({effects:pi.of(i.messages.add(o))})}}onMessageRemoved(e){const{editor:t}=this.textEditor,i=t.state.field(fi,!1);if(i){const o=this.createMessage(e.data);t.dispatch({effects:pi.of(i.messages.remove(o))})}}onDecorationChanged(e){for(const t of this.plugins)t.decorationChanged(e.data,this.textEditor)}async toolbarItems(){const e=await super.toolbarItems(),i=[];for(const t of this.plugins)e.push(...t.leftToolbarItems()),i.push(...t.rightToolbarItems());return i.length?[...e,new t.Toolbar.ToolbarSeparator(!0),...i]:e}getErrorPopoverContent(e){const t=e,i=e.target,o=i.enclosingNodeOrSelfWithClass("cm-messageIcon-error")||i.enclosingNodeOrSelfWithClass("cm-messageIcon-issue");if(!o)return null;const n=this.textEditor.state.field(fi,!1);if(!n||0===n.messages.rows.length)return null;const{editor:r}=this.textEditor,s=r.posAtCoords(t);if(null===s)return null;const a=r.state.doc.lineAt(s);if(s!==a.to)return null;const c=n.messages.rows.find((e=>e[0].lineNumber()===a.number-1));if(!c)return null;const l=o.classList.contains("cm-messageIcon-issue"),d=c.filter((e=>e.level()===v.UISourceCode.Message.Level.Issue===l));if(!d.length)return null;const u=o?o.boxInWindow():new AnchorBox(t.clientX,t.clientY,1,1),h=function(e){const t=[];for(let i=0;i<e.length;i++){t[i]=0;for(let o=0;o<=i;o++)if(e[o].isEqual(e[i])){t[o]++;break}}return t}(d),p=document.createElement("div");p.classList.add("text-editor-messages-description-container");for(let e=0;e<d.length;e++)h[e]&&p.appendChild(Si(d[e],h[e]));return{box:u,hide(){},show:async e=>(e.contentElement.append(p),!0)}}#d(){if(this.#l)return;this.#l=!0;const e=i.ResourceType.ResourceType.mimeFromURL(this.uiSourceCodeInternal.url()),t=i.ResourceType.ResourceType.mediaTypeForMetrics(e??"",this.uiSourceCodeInternal.contentType().isFromSourceMap(),S.TextUtils.isMinified(this.uiSourceCodeInternal.content()));a.userMetrics.sourcesPanelFileOpened(t)}}function ai(e){return e===v.UISourceCode.Message.Level.Error?{color:"var(--icon-error)",width:"16px",height:"14px",iconName:"cross-circle-filled"}:e===v.UISourceCode.Message.Level.Warning?{color:"var(--icon-warning)",width:"18px",height:"14px",iconName:"warning-filled"}:e===v.UISourceCode.Message.Level.Issue?{color:"var(--icon-warning)",width:"17px",height:"14px",iconName:"issue-exclamation-filled"}:{color:"var(--icon-error)",width:"16px",height:"14px",iconName:"cross-circle-filled"}}function ci(e,t){const i={[v.UISourceCode.Message.Level.Issue]:2,[v.UISourceCode.Message.Level.Warning]:3,[v.UISourceCode.Message.Level.Error]:4};return i[e.level()]-i[t.level()]}(ni||(ni={})).ToolbarItemsChanged="ToolbarItemsChanged";const li=new n.Compartment;class di{origin;#u;#h;constructor(e,t,i){this.origin=e,this.#u=t,this.#h=i}level(){return this.origin.level()}text(){return this.origin.text()}clickHandler(){return this.origin.clickHandler()}lineNumber(){return this.#u}columnNumber(){return this.#h}isEqual(e){return this.origin.isEqual(e.origin)}}function ui(e,t){const i=t.lineNumber();let o=0;for(;o<e.length;o++){const n=e[o][0].lineNumber()-i;if(0===n)return e[o]=e[o].concat(t),e;if(n>0)break}return e.splice(o,0,[t]),e}class hi{rows;constructor(e){this.rows=e}static create(e){const t=[];for(const i of e)ui(t,i);return new hi(t)}remove(e){const t=this.rows.slice();return function(e,t){for(let i=0;i<e.length;i++)if(e[i][0].lineNumber()===t.lineNumber()){const o=e[i].filter((e=>!e.isEqual(t)));o.length?e[i]=o:e.splice(i,1);break}}(t,e),new hi(t)}add(e){return new hi(ui(this.rows.slice(),e))}}const pi=n.StateEffect.define(),gi=n.Decoration.mark({class:"cm-waveUnderline"});class mi extends n.WidgetType{messages;constructor(e){super(),this.messages=e}eq(e){return e.messages===this.messages}toDOM(){const e=document.createElement("span");e.classList.add("cm-messageIcon");const t=this.messages.filter((e=>e.level()!==v.UISourceCode.Message.Level.Issue));if(t.length){const i=t.sort(ci)[t.length-1],o=e.appendChild(new r.Icon.Icon);o.data=ai(i.level()),o.classList.add("cm-messageIcon-error")}const i=this.messages.find((e=>e.level()===v.UISourceCode.Message.Level.Issue));if(i){const t=e.appendChild(new r.Icon.Icon);t.data=ai(v.UISourceCode.Message.Level.Issue),t.classList.add("cm-messageIcon-issue"),t.addEventListener("click",(()=>(i.clickHandler()||Math.min)()))}return e}ignoreEvents(){return!0}}class bi{messages;decorations;constructor(e,t){this.messages=e,this.decorations=t}static create(e,t){const i=new n.RangeSetBuilder;for(const o of e.rows){const e=t.line(o[0].lineNumber()+1),r=o.reduce(((e,t)=>Math.min(e,t.columnNumber()||0)),e.length);r<e.length&&i.add(e.from+r,e.to,gi),i.add(e.to,e.to,n.Decoration.widget({side:1,widget:new mi(o)}))}return new bi(e,i.finish())}apply(e){let t=this;e.docChanged&&(t=new bi(this.messages,this.decorations.map(e.changes)));for(const i of e.effects)i.is(pi)&&(t=bi.create(i.value,e.state.doc));return t}}const fi=n.StateField.define({create:e=>bi.create(new hi([]),e.doc),update:(e,t)=>e.apply(t),provide:e=>n.Prec.lowest(n.EditorView.decorations.from(e,(e=>e.decorations)))});function Si(e,t){const i=document.createElement("div");if(i.classList.add("text-editor-row-message"),i.style.display="flex",i.style.alignItems="center",i.style.gap="4px",1===t){const t=i.appendChild(new r.Icon.Icon);t.data=function(e){return e.origin instanceof T.SourceFrameIssuesManager.IssueMessage?{...L.IssueCounter.getIssueKindIconData(e.origin.getIssueKind()),width:"12px",height:"12px"}:ai(e.level())}(e),t.classList.add("text-editor-row-message-icon"),t.addEventListener("click",(()=>(e.clickHandler()||Math.min)()))}else{const o=document.createElement("span",{is:"dt-small-bubble"});o.textContent=String(t),o.classList.add("text-editor-row-message-repeat-count"),o.style.flexShrink="0",i.appendChild(o),o.type=function(e){switch(e){case v.UISourceCode.Message.Level.Error:return"error";case v.UISourceCode.Message.Level.Warning:case v.UISourceCode.Message.Level.Issue:return"warning"}}(e.level())}const o=i.createChild("div");for(const t of e.text().split("\n"))o.createChild("div").textContent=t;return i}const vi=n.EditorView.baseTheme({".cm-tooltip-message":{padding:"4px"},".cm-waveUnderline":{backgroundImage:"var(--image-file-errorWave)",backgroundRepeat:"repeat-x",backgroundPosition:"bottom",paddingBottom:"1px"},".cm-messageIcon":{cursor:"pointer","& > *":{verticalAlign:"text-bottom",marginLeft:"2px"}},".cm-messageIcon-issue, .cm-messageIcon-error":{marginTop:"-1px",marginBottom:"-1px"}});var Ci=Object.freeze({__proto__:null,UISourceCodeFrame:si,get Events(){return ni}});const wi={areYouSureYouWantToCloseUnsaved:"Are you sure you want to close unsaved file: {PH1}?",unableToLoadThisContent:"Unable to load this content.",changesToThisFileWereNotSavedTo:"Changes to this file were not saved to file system."},Ii=e.i18n.registerUIStrings("panels/sources/TabbedEditorContainer.ts",wi),xi=e.i18n.getLocalizedString.bind(void 0,Ii);let yi=0;class Ei extends i.ObjectWrapper.ObjectWrapper{delegate;tabbedPane;tabIds;files;previouslyViewedFilesSetting;history;uriToUISourceCode;idToUISourceCode;currentFileInternal;currentView;scrollTimer;reentrantShow;constructor(e,i,o,n){super(),this.delegate=e,this.tabbedPane=new t.TabbedPane.TabbedPane,this.tabbedPane.setPlaceholderElement(o,n),this.tabbedPane.setTabDelegate(new Fi(this)),this.tabbedPane.setCloseableTabs(!0),this.tabbedPane.setAllowTabReorder(!0,!0),this.tabbedPane.addEventListener(t.TabbedPane.Events.TabClosed,this.tabClosed,this),this.tabbedPane.addEventListener(t.TabbedPane.Events.TabSelected,this.tabSelected,this),u.Persistence.PersistenceImpl.instance().addEventListener(u.Persistence.Events.BindingCreated,this.onBindingCreated,this),u.Persistence.PersistenceImpl.instance().addEventListener(u.Persistence.Events.BindingRemoved,this.onBindingRemoved,this),u.NetworkPersistenceManager.NetworkPersistenceManager.instance().addEventListener(u.NetworkPersistenceManager.Events.RequestsForHeaderOverridesFileChanged,this.#a,this),this.tabIds=new Map,this.files=new Map,this.previouslyViewedFilesSetting=i,this.history=Pi.fromObject(this.previouslyViewedFilesSetting.get()),this.uriToUISourceCode=new Map,this.idToUISourceCode=new Map,this.reentrantShow=!1}onBindingCreated(e){const t=e.data;this.updateFileTitle(t.fileSystem);const i=this.tabIds.get(t.network);let o=this.tabIds.get(t.fileSystem);const n=this.currentFileInternal===t.network,r=Li(t.network),s=this.history.selectionRange(r),a=this.history.scrollLineNumber(r);if(this.history.remove(r),i){if(!o){const e=this.tabbedPane.tabView(i),n=this.tabbedPane.tabIndex(i);if(e instanceof si)this.delegate.recycleUISourceCodeFrame(e,t.fileSystem),o=this.appendFileTab(t.fileSystem,!1,n,e);else{o=this.appendFileTab(t.fileSystem,!1,n);const e=this.tabbedPane.tabView(o);this.restoreEditorProperties(e,s,a)}}this.closeTabs([i],!0),n&&this.tabbedPane.selectTab(o,!1),this.updateHistory()}}#a(e){this.updateFileTitle(e.data)}onBindingRemoved(e){const t=e.data;this.updateFileTitle(t.fileSystem)}get view(){return this.tabbedPane}get visibleView(){return this.tabbedPane.visibleView}fileViews(){return this.tabbedPane.tabViews()}leftToolbar(){return this.tabbedPane.leftToolbar()}rightToolbar(){return this.tabbedPane.rightToolbar()}show(e){this.tabbedPane.show(e)}showFile(e){const o=u.Persistence.PersistenceImpl.instance().binding(e);e=o?o.fileSystem:e;const n=t.Context.Context.instance().flavor(Ri);if(n?.currentSourceFrame()?.contentSet&&this.currentFileInternal===e&&n?.currentUISourceCode()===e)i.EventTarget.fireEvent("source-file-loaded",e.displayName(!0));else{if(e.project().type()===v.Workspace.projectTypes.Debugger){const t=d.DefaultScriptMapping.DefaultScriptMapping.scriptForUISourceCode(e);t&&t.isInlineScript()&&!t.hasSourceURL&&(t.isModule?a.userMetrics.vmInlineScriptContentShown(0):a.userMetrics.vmInlineScriptContentShown(1))}this.innerShowFile(e,!0)}}closeFile(e){const t=this.tabIds.get(e);t&&this.closeTabs([t])}closeAllFiles(){this.closeTabs(this.tabbedPane.tabIds())}historyUISourceCodes(){const e=[];for(const{url:t,resourceType:i}of this.history.keys()){const o=this.uriToUISourceCode.get(t);void 0!==o&&o.contentType()===i&&e.push(o)}return e}selectNextTab(){this.tabbedPane.selectNextTab()}selectPrevTab(){this.tabbedPane.selectPrevTab()}addViewListeners(){this.currentView&&this.currentView instanceof p.SourceFrame.SourceFrameImpl&&(this.currentView.addEventListener("EditorUpdate",this.onEditorUpdate,this),this.currentView.addEventListener("EditorScroll",this.onScrollChanged,this))}removeViewListeners(){this.currentView&&this.currentView instanceof p.SourceFrame.SourceFrameImpl&&(this.currentView.removeEventListener("EditorUpdate",this.onEditorUpdate,this),this.currentView.removeEventListener("EditorScroll",this.onScrollChanged,this))}onScrollChanged(){if(this.currentView instanceof p.SourceFrame.SourceFrameImpl&&(this.scrollTimer&&clearTimeout(this.scrollTimer),this.scrollTimer=window.setTimeout((()=>this.previouslyViewedFilesSetting.set(this.history.toObject())),100),this.currentFileInternal)){const{editor:e}=this.currentView.textEditor,t=e.lineBlockAtHeight(e.scrollDOM.getBoundingClientRect().top-e.documentTop),i=e.state.doc.lineAt(t.from).number-1;this.history.updateScrollLineNumber(Li(this.currentFileInternal),i)}}onEditorUpdate({data:e}){if(e.docChanged||e.selectionSet){const{main:t}=e.state.selection,i=e.state.doc.lineAt(t.from),o=e.state.doc.lineAt(t.to),n=new S.TextRange.TextRange(i.number-1,t.from-i.from,o.number-1,t.to-o.from);this.currentFileInternal&&this.history.updateSelectionRange(Li(this.currentFileInternal),n),this.previouslyViewedFilesSetting.set(this.history.toObject()),this.currentFileInternal&&x.ExtensionServer.ExtensionServer.instance().sourceSelectionChanged(this.currentFileInternal.url(),n)}}innerShowFile(e,t){if(this.reentrantShow)return;const i=this.canonicalUISourceCode(e),o=u.Persistence.PersistenceImpl.instance().binding(e);if(e=o?o.fileSystem:e,this.currentFileInternal===e)return;this.removeViewListeners(),this.currentFileInternal=e;try{this.reentrantShow=!0;const e=this.tabIds.get(i)||this.appendFileTab(i,t);this.tabbedPane.selectTab(e,t)}finally{this.reentrantShow=!1}t&&this.editorSelectedByUserAction();const n=this.currentView;this.currentView=this.visibleView,this.addViewListeners(),this.currentView instanceof si&&this.currentView.uiSourceCode()!==e&&(this.delegate.recycleUISourceCodeFrame(this.currentView,e),e.project().type()!==v.Workspace.projectTypes.FileSystem&&e.disableEdit());const r={currentFile:this.currentFileInternal,currentView:this.currentView,previousView:n,userGesture:t};this.dispatchEventToListeners(ki.EditorSelected,r)}titleForFile(e){let t=c.StringUtilities.trimMiddle(e.displayName(!0),30);return e.isDirty()&&(t+="*"),t}maybeCloseTab(e,t){const i=this.files.get(e);if(!i)return!1;return!(i.isDirty()&&i.project().canSetFileContent()&&!confirm(xi(wi.areYouSureYouWantToCloseUnsaved,{PH1:i.name()})))&&(i.resetWorkingCopy(),t&&this.tabbedPane.selectTab(t,!0),this.tabbedPane.closeTab(e,!0),!0)}closeTabs(e,t){const i=[],o=[];for(let n=0;n<e.length;++n){const r=e[n],s=this.files.get(r);s&&(!t&&s.isDirty()?i.push(r):o.push(r))}i.length&&this.tabbedPane.selectTab(i[0],!0),this.tabbedPane.closeTabs(o,!0);for(let e=0;e<i.length;++e){const t=e+1<i.length?i[e+1]:null;if(!this.maybeCloseTab(i[e],t))break}}onContextMenu(e,t){const i=this.files.get(e);i&&t.appendApplicableItems(i)}canonicalUISourceCode(e){const t=this.idToUISourceCode.get(e.canononicalScriptId());return t||(this.idToUISourceCode.set(e.canononicalScriptId(),e),this.uriToUISourceCode.set(e.url(),e),e)}addUISourceCode(e){const t=this.canonicalUISourceCode(e),i=t!==e,o=u.Persistence.PersistenceImpl.instance().binding(t);if(e=o?o.fileSystem:t,i&&e.project().type()!==v.Workspace.projectTypes.FileSystem&&e.disableEdit(),this.currentFileInternal?.canononicalScriptId()===e.canononicalScriptId())return;const n=this.history.index(Li(e));if(-1===n)return;if(this.tabIds.has(e)||this.appendFileTab(e,!1),!n)return void this.innerShowFile(e,!1);if(!this.currentFileInternal)return;const r=y.ScriptSnippetFileSystem.isSnippetsUISourceCode(this.currentFileInternal),s=y.ScriptSnippetFileSystem.isSnippetsUISourceCode(e);this.history.index(Li(this.currentFileInternal))&&r&&!s&&this.innerShowFile(e,!1)}removeUISourceCode(e){this.removeUISourceCodes([e])}removeUISourceCodes(e){const t=[];for(const i of e){const e=this.tabIds.get(i);e&&t.push(e),this.uriToUISourceCode.get(i.url())===i&&this.uriToUISourceCode.delete(i.url()),this.idToUISourceCode.get(i.canononicalScriptId())===i&&this.idToUISourceCode.delete(i.canononicalScriptId())}this.tabbedPane.closeTabs(t)}editorClosedByUserAction(e){this.history.remove(Li(e)),this.updateHistory()}editorSelectedByUserAction(){this.updateHistory()}updateHistory(){const e=[];for(const t of this.tabbedPane.lastOpenedTabIds(Ti)){const i=this.files.get(t);void 0!==i&&e.push(Li(i))}this.history.update(e),this.previouslyViewedFilesSetting.set(this.history.toObject())}tooltipForFile(e){return(e=u.Persistence.PersistenceImpl.instance().network(e)||e).url()}appendFileTab(e,t,i,o){const n=o||this.delegate.viewForFile(e),r=this.titleForFile(e),s=this.tooltipForFile(e),a=this.generateTabId();if(this.tabIds.set(e,a),this.files.set(a,e),!o){const t=this.history.selectionRange(Li(e)),i=this.history.scrollLineNumber(Li(e));this.restoreEditorProperties(n,t,i)}return this.tabbedPane.appendTab(a,r,n,s,t,void 0,void 0,i),this.updateFileTitle(e),this.addUISourceCodeListeners(e),e.loadError()?this.addLoadErrorIcon(a):e.contentLoaded()||e.requestContent().then((t=>{e.loadError()&&this.addLoadErrorIcon(a)})),a}addLoadErrorIcon(e){const i=new r.Icon.Icon;i.data={iconName:"cross-circle-filled",color:"var(--icon-error)",width:"14px",height:"14px"},t.Tooltip.Tooltip.install(i,xi(wi.unableToLoadThisContent)),this.tabbedPane.tabView(e)&&this.tabbedPane.setTabIcon(e,i)}restoreEditorProperties(e,t,i){const o=e instanceof p.SourceFrame.SourceFrameImpl?e:null;o&&(t&&o.setSelection(t),"number"==typeof i&&o.scrollToLine(i))}tabClosed(e){const{tabId:t,isUserGesture:i}=e.data,o=this.files.get(t);this.currentFileInternal&&this.currentFileInternal.canononicalScriptId()===o?.canononicalScriptId()&&(this.removeViewListeners(),this.currentView=null,this.currentFileInternal=null),o&&this.tabIds.delete(o),this.files.delete(t),o&&(this.removeUISourceCodeListeners(o),this.dispatchEventToListeners(ki.EditorClosed,o),i&&this.editorClosedByUserAction(o))}tabSelected(e){const{tabId:t,isUserGesture:i}=e.data,o=this.files.get(t);o&&this.innerShowFile(o,i)}addUISourceCodeListeners(e){e.addEventListener(v.UISourceCode.Events.TitleChanged,this.uiSourceCodeTitleChanged,this),e.addEventListener(v.UISourceCode.Events.WorkingCopyChanged,this.uiSourceCodeWorkingCopyChanged,this),e.addEventListener(v.UISourceCode.Events.WorkingCopyCommitted,this.uiSourceCodeWorkingCopyCommitted,this)}removeUISourceCodeListeners(e){e.removeEventListener(v.UISourceCode.Events.TitleChanged,this.uiSourceCodeTitleChanged,this),e.removeEventListener(v.UISourceCode.Events.WorkingCopyChanged,this.uiSourceCodeWorkingCopyChanged,this),e.removeEventListener(v.UISourceCode.Events.WorkingCopyCommitted,this.uiSourceCodeWorkingCopyCommitted,this)}updateFileTitle(e){const i=this.tabIds.get(e);if(i){const o=this.titleForFile(e),n=this.tooltipForFile(e);this.tabbedPane.changeTabTitle(i,o,n);let s=null;e.loadError()?(s=new r.Icon.Icon,s.data={iconName:"cross-circle-filled",color:"var(--icon-error)",width:"14px",height:"14px"},t.Tooltip.Tooltip.install(s,xi(wi.unableToLoadThisContent))):u.Persistence.PersistenceImpl.instance().hasUnsavedCommittedChanges(e)?(s=new r.Icon.Icon,s.data={iconName:"warning-filled",color:"var(--icon-warning)",width:"14px",height:"14px"},t.Tooltip.Tooltip.install(s,xi(wi.changesToThisFileWereNotSavedTo))):s=u.PersistenceUtils.PersistenceUtils.iconForUISourceCode(e),this.tabbedPane.setTabIcon(i,s)}}uiSourceCodeTitleChanged(e){const t=e.data;this.updateFileTitle(t),this.updateHistory();for(const[e,i]of this.uriToUISourceCode)i===t&&e!==i.url()&&this.uriToUISourceCode.delete(e);for(const[e,i]of this.idToUISourceCode)i===t&&e!==i.canononicalScriptId()&&this.idToUISourceCode.delete(e);this.canonicalUISourceCode(t)}uiSourceCodeWorkingCopyChanged(e){const t=e.data;this.updateFileTitle(t)}uiSourceCodeWorkingCopyCommitted(e){const t=e.data.uiSourceCode;this.updateFileTitle(t)}generateTabId(){return"tab_"+yi++}currentFile(){return this.currentFileInternal||null}}var ki;!function(e){e.EditorSelected="EditorSelected",e.EditorClosed="EditorClosed"}(ki||(ki={}));const Ti=30;function Li(e){return{url:e.url(),resourceType:e.contentType()}}class Mi{url;resourceType;selectionRange;scrollLineNumber;constructor(e,t,i,o){this.url=e,this.resourceType=t,this.selectionRange=i,this.scrollLineNumber=o}static fromObject(e){const t=i.ResourceType.ResourceType.fromName(e.resourceTypeName);if(null===t)throw new TypeError(`Invalid resource type name "${e.resourceTypeName}"`);const o=e.selectionRange?S.TextRange.TextRange.fromObject(e.selectionRange):void 0;return new Mi(e.url,t,o,e.scrollLineNumber)}toObject(){return this.url.length>=4096?null:{url:this.url,resourceTypeName:this.resourceType.name(),selectionRange:this.selectionRange,scrollLineNumber:this.scrollLineNumber}}}class Pi{items;constructor(e){this.items=e}static fromObject(e){const t=[];for(const i of e)try{t.push(Mi.fromObject(i))}catch{}return new Pi(t)}index({url:e,resourceType:t}){return this.items.findIndex((i=>i.url===e&&i.resourceType===t))}selectionRange(e){const t=this.index(e);if(-1!==t)return this.items[t].selectionRange}updateSelectionRange(e,t){if(!t)return;const i=this.index(e);-1!==i&&(this.items[i].selectionRange=t)}scrollLineNumber(e){const t=this.index(e);if(-1!==t)return this.items[t].scrollLineNumber}updateScrollLineNumber(e,t){const i=this.index(e);-1!==i&&(this.items[i].scrollLineNumber=t)}update(e){for(let t=e.length-1;t>=0;--t){const i=this.index(e[t]);let o;-1!==i?(o=this.items[i],this.items.splice(i,1)):o=new Mi(e[t].url,e[t].resourceType),this.items.unshift(o)}}remove(e){const t=this.index(e);-1!==t&&this.items.splice(t,1)}toObject(){const e=[];for(const t of this.items){const i=t.toObject();if(i&&e.push(i),e.length===Ti)break}return e}keys(){return this.items}}class Fi{editorContainer;constructor(e){this.editorContainer=e}closeTabs(e,t){this.editorContainer.closeTabs(t)}onContextMenu(e,t){this.editorContainer.onContextMenu(e,t)}}var Di=Object.freeze({__proto__:null,TabbedEditorContainer:Ei,get Events(){return ki},HistoryItem:Mi,History:Pi,EditorContainerTabDelegate:Fi});const Ni={openFile:"Open file",runCommand:"Run command",dropInAFolderToAddToWorkspace:"Drop in a folder to add to workspace",sourceViewActions:"Source View Actions"},Ai=e.i18n.registerUIStrings("panels/sources/SourcesView.ts",Ni),Ui=e.i18n.getLocalizedString.bind(void 0,Ai);class Ri extends(i.ObjectWrapper.eventMixin(t.Widget.VBox)){placeholderOptionArray;selectedIndex;searchableViewInternal;sourceViewByUISourceCode;editorContainer;historyManager;toolbarContainerElementInternal;scriptViewToolbar;bottomToolbarInternal;toolbarChangedListener;shortcuts;focusedPlaceholderElement;searchView;searchConfig;constructor(){super(),this.element.id="sources-panel-sources-view",this.setMinimumAndPreferredSizes(88,52,150,100),this.placeholderOptionArray=[],this.selectedIndex=0;const e=v.Workspace.WorkspaceImpl.instance();this.searchableViewInternal=new t.SearchableView.SearchableView(this,this,"sourcesViewSearchConfig"),this.searchableViewInternal.setMinimalSearchQuerySize(0),this.searchableViewInternal.show(this.element),this.sourceViewByUISourceCode=new Map,this.editorContainer=new Ei(this,i.Settings.Settings.instance().createLocalSetting("previouslyViewedFiles",[]),this.placeholderElement(),this.focusedPlaceholderElement),this.editorContainer.show(this.searchableViewInternal.element),this.editorContainer.addEventListener(ki.EditorSelected,this.editorSelected,this),this.editorContainer.addEventListener(ki.EditorClosed,this.editorClosed,this),this.historyManager=new Nt(this),this.toolbarContainerElementInternal=this.element.createChild("div","sources-toolbar"),this.scriptViewToolbar=new t.Toolbar.Toolbar("",this.toolbarContainerElementInternal),this.scriptViewToolbar.element.style.flex="auto",this.bottomToolbarInternal=new t.Toolbar.Toolbar("",this.toolbarContainerElementInternal),this.toolbarChangedListener=null,t.UIUtils.startBatchUpdate(),e.uiSourceCodes().forEach(this.addUISourceCode.bind(this)),t.UIUtils.endBatchUpdate(),e.addEventListener(v.Workspace.Events.UISourceCodeAdded,this.uiSourceCodeAdded,this),e.addEventListener(v.Workspace.Events.UISourceCodeRemoved,this.uiSourceCodeRemoved,this),e.addEventListener(v.Workspace.Events.ProjectRemoved,this.projectRemoved.bind(this),this),window.opener||window.addEventListener("beforeunload",(function(e){if(e.returnValue)return;const o=[],n=v.Workspace.WorkspaceImpl.instance().projectsForType(v.Workspace.projectTypes.FileSystem);for(const e of n)for(const t of e.uiSourceCodes())t.isDirty()&&o.push(t);if(o.length){e.returnValue=!0,t.ViewManager.ViewManager.instance().showView("sources");for(const e of o)i.Revealer.reveal(e)}}),!0),this.shortcuts=new Map,this.element.addEventListener("keydown",this.handleKeyDown.bind(this),!1)}placeholderElement(){this.placeholderOptionArray=[];const e=[{actionId:"quickOpen.show",description:Ui(Ni.openFile)},{actionId:"commandMenu.show",description:Ui(Ni.runCommand)},{actionId:"sources.add-folder-to-workspace",description:Ui(Ni.dropInAFolderToAddToWorkspace),condition:I.Runtime.ConditionName.NOT_SOURCES_HIDE_ADD_FOLDER}],i=document.createElement("div"),o=i.createChild("div","tabbed-pane-placeholder");o.addEventListener("keydown",this.placeholderOnKeyDown.bind(this),!1),t.ARIAUtils.markAsList(o),t.ARIAUtils.setLabel(o,Ui(Ni.sourceViewActions));for(let i=0;i<e.length;i++){const n=e[i],{condition:r}=n;if(void 0!==r&&!I.Runtime.Runtime.isDescriptorEnabled({experiment:void 0,condition:r}))continue;const s=t.ShortcutRegistry.ShortcutRegistry.instance().shortcutTitleForAction(n.actionId),a=o.createChild("div");t.ARIAUtils.markAsListitem(a);const c=a.createChild("div","tabbed-pane-placeholder-row");c.tabIndex=-1,t.ARIAUtils.markAsButton(c),s?(c.createChild("div","tabbed-pane-placeholder-key").textContent=s,c.createChild("div","tabbed-pane-placeholder-value").textContent=n.description):c.createChild("div","tabbed-pane-no-shortcut").textContent=n.description;const l=t.ActionRegistry.ActionRegistry.instance().action(n.actionId);l&&this.placeholderOptionArray.push({element:c,handler(){l.execute()}})}return I.Runtime.Runtime.isDescriptorEnabled({experiment:void 0,condition:I.Runtime.ConditionName.NOT_SOURCES_HIDE_ADD_FOLDER})&&i.appendChild(t.XLink.XLink.create("https://developer.chrome.com/docs/devtools/workspaces/","Learn more about Workspaces")),i}placeholderOnKeyDown(e){const i=e;if(c.KeyboardUtilities.isEnterOrSpaceKey(i))return void this.placeholderOptionArray[this.selectedIndex].handler();let o=0;"ArrowDown"===i.key?o=1:"ArrowUp"===i.key&&(o=-1);const n=Math.max(Math.min(this.placeholderOptionArray.length-1,this.selectedIndex+o),0),r=this.placeholderOptionArray[n].element,s=this.placeholderOptionArray[this.selectedIndex].element;r!==s&&(s.tabIndex=-1,r.tabIndex=0,t.ARIAUtils.setSelected(s,!1),t.ARIAUtils.setSelected(r,!0),this.selectedIndex=n,r.focus())}static defaultUISourceCodeScores(){const e=new Map,i=t.Context.Context.instance().flavor(Ri);if(i){const t=i.editorContainer.historyUISourceCodes();for(let i=1;i<t.length;++i)e.set(t[i],t.length-i)}return e}leftToolbar(){return this.editorContainer.leftToolbar()}rightToolbar(){return this.editorContainer.rightToolbar()}bottomToolbar(){return this.bottomToolbarInternal}registerShortcuts(e,t){for(let i=0;i<e.length;++i)this.shortcuts.set(e[i].key,t)}handleKeyDown(e){const i=t.KeyboardShortcut.KeyboardShortcut.makeKeyFromEvent(e),o=this.shortcuts.get(i);o&&o()&&e.consume(!0)}wasShown(){super.wasShown(),this.registerCSSFiles([Rt]),t.Context.Context.instance().setFlavor(Ri,this)}willHide(){t.Context.Context.instance().setFlavor(Ri,null),super.willHide()}toolbarContainerElement(){return this.toolbarContainerElementInternal}searchableView(){return this.searchableViewInternal}visibleView(){return this.editorContainer.visibleView}currentSourceFrame(){const e=this.visibleView();return e instanceof si?e:null}currentUISourceCode(){return this.editorContainer.currentFile()}onCloseEditorTab(){const e=this.editorContainer.currentFile();return!!e&&(this.editorContainer.closeFile(e),!0)}onJumpToPreviousLocation(){this.historyManager.rollback()}onJumpToNextLocation(){this.historyManager.rollover()}uiSourceCodeAdded(e){const t=e.data;this.addUISourceCode(t)}addUISourceCode(e){e.project().isServiceProject()||e.project().type()===v.Workspace.projectTypes.FileSystem&&"overrides"===u.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.fileSystemType(e.project())||this.editorContainer.addUISourceCode(e)}uiSourceCodeRemoved(e){const t=e.data;this.removeUISourceCodes([t])}removeUISourceCodes(e){this.editorContainer.removeUISourceCodes(e);for(let t=0;t<e.length;++t)this.removeSourceFrame(e[t]),this.historyManager.removeHistoryForSourceCode(e[t])}projectRemoved(e){const t=e.data.uiSourceCodes();this.removeUISourceCodes([...t])}updateScriptViewToolbarItems(){const e=this.visibleView();e instanceof t.View.SimpleView&&e.toolbarItems().then((e=>{this.scriptViewToolbar.removeToolbarItems();for(const e of Wi())this.scriptViewToolbar.appendToolbarItem(e.getOrCreateButton(this));e.map((e=>this.scriptViewToolbar.appendToolbarItem(e)))}))}showSourceLocation(e,t,i,o){const n=this.currentSourceFrame();n&&this.historyManager.updateCurrentState(n.uiSourceCode(),n.textEditor.state.selection.main.head),this.editorContainer.showFile(e);const r=this.currentSourceFrame();r&&t&&r.revealPosition(t,!o);const s=this.visibleView();!i&&s&&s.focus()}createSourceView(e){let t,o;const n=e.contentType();n===i.ResourceType.resourceTypes.Image?o=new p.ImageView.ImageView(e.mimeType(),e):n===i.ResourceType.resourceTypes.Font?o=new p.FontView.FontView(e.mimeType(),e):e.name()===qi&&I.Runtime.experiments.isEnabled(I.Runtime.ExperimentName.HEADER_OVERRIDES)?o=new w.HeadersView.HeadersView(e):t=new si(e),t&&this.historyManager.trackSourceFrameCursorJumps(t),e.addEventListener(v.UISourceCode.Events.TitleChanged,this.#p,this);const r=t||o;return this.sourceViewByUISourceCode.set(e,r),r}#g(e){return e instanceof p.ImageView.ImageView?Gi.ImageView:e instanceof p.FontView.FontView?Gi.FontView:e instanceof w.HeadersView.HeadersView?Gi.HeadersView:Gi.SourceView}#m(e){if(e.name()===qi&&I.Runtime.experiments.isEnabled(I.Runtime.ExperimentName.HEADER_OVERRIDES))return Gi.HeadersView;switch(e.contentType()){case i.ResourceType.resourceTypes.Image:return Gi.ImageView;case i.ResourceType.resourceTypes.Font:return Gi.FontView;default:return Gi.SourceView}}#p(e){const t=e.data,i=this.sourceViewByUISourceCode.get(t);i&&this.#g(i)!==this.#m(t)&&(this.removeUISourceCodes([t]),this.showSourceLocation(t))}getSourceView(e){return this.sourceViewByUISourceCode.get(e)}getOrCreateSourceView(e){return this.sourceViewByUISourceCode.get(e)||this.createSourceView(e)}recycleUISourceCodeFrame(e,t){e.uiSourceCode().removeEventListener(v.UISourceCode.Events.TitleChanged,this.#p,this),this.sourceViewByUISourceCode.delete(e.uiSourceCode()),e.setUISourceCode(t),this.sourceViewByUISourceCode.set(t,e),t.addEventListener(v.UISourceCode.Events.TitleChanged,this.#p,this)}viewForFile(e){return this.getOrCreateSourceView(e)}removeSourceFrame(e){const t=this.sourceViewByUISourceCode.get(e);this.sourceViewByUISourceCode.delete(e),t&&t instanceof si&&t.dispose(),e.removeEventListener(v.UISourceCode.Events.TitleChanged,this.#p,this)}editorClosed(e){const t=e.data;this.historyManager.removeHistoryForSourceCode(t);let i=!1;this.editorContainer.currentFile()||(i=!0),this.removeToolbarChangedListener(),this.updateScriptViewToolbarItems(),this.searchableViewInternal.resetSearch();const o={uiSourceCode:t,wasSelected:i};this.dispatchEventToListeners(Bi.EditorClosed,o)}editorSelected(e){const t=e.data.previousView instanceof si?e.data.previousView:null;t&&t.setSearchableView(null);const i=e.data.currentView instanceof si?e.data.currentView:null;i&&i.setSearchableView(this.searchableViewInternal),this.searchableViewInternal.setReplaceable(Boolean(i?.canEditSource())),this.searchableViewInternal.refreshSearch(),this.updateToolbarChangedListener(),this.updateScriptViewToolbarItems();const o=this.editorContainer.currentFile();o&&this.dispatchEventToListeners(Bi.EditorSelected,o)}removeToolbarChangedListener(){this.toolbarChangedListener&&i.EventTarget.removeEventListeners([this.toolbarChangedListener]),this.toolbarChangedListener=null}updateToolbarChangedListener(){this.removeToolbarChangedListener();const e=this.currentSourceFrame();e&&(this.toolbarChangedListener=e.addEventListener(ni.ToolbarItemsChanged,this.updateScriptViewToolbarItems,this))}onSearchCanceled(){this.searchView&&this.searchView.onSearchCanceled(),delete this.searchView,delete this.searchConfig}performSearch(e,t,i){const o=this.currentSourceFrame();o&&(this.searchView=o,this.searchConfig=e,this.searchView.performSearch(this.searchConfig,t,i))}jumpToNextSearchResult(){this.searchView&&(this.searchConfig&&this.searchView!==this.currentSourceFrame()?this.performSearch(this.searchConfig,!0):this.searchView.jumpToNextSearchResult())}jumpToPreviousSearchResult(){if(this.searchView)return this.searchConfig&&this.searchView!==this.currentSourceFrame()?(this.performSearch(this.searchConfig,!0),void(this.searchView&&this.searchView.jumpToLastSearchResult())):void this.searchView.jumpToPreviousSearchResult()}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}replaceSelectionWith(e,t){const i=this.currentSourceFrame();i?i.replaceSelectionWith(e,t):console.assert(Boolean(i))}replaceAllWith(e,t){const i=this.currentSourceFrame();i?i.replaceAllWith(e,t):console.assert(Boolean(i))}showOutlineQuickOpen(){k.QuickOpen.QuickOpenImpl.show("@")}showGoToLineQuickOpen(){this.editorContainer.currentFile()&&k.QuickOpen.QuickOpenImpl.show(":")}save(){this.saveSourceFrame(this.currentSourceFrame())}saveAll(){this.editorContainer.fileViews().forEach(this.saveSourceFrame.bind(this))}saveSourceFrame(e){if(!(e instanceof si))return;e.commitEditing()}toggleBreakpointsActiveState(e){this.editorContainer.view.element.classList.toggle("breakpoints-deactivated",!e)}}var Bi;!function(e){e.EditorClosed="EditorClosed",e.EditorSelected="EditorSelected"}(Bi||(Bi={}));const Vi=[];function Oi(e){Vi.push(e)}function Wi(){return Vi.map((e=>e()))}let ji,Hi;class _i{static instance(e={forceNew:null}){const{forceNew:t}=e;return ji&&!t||(ji=new _i),ji}static nextFile(e){function t(e){const t=e.lastIndexOf(".");return e.substr(0,-1!==t?t:e.length).toLowerCase()}const o=[],n=e.parentURL(),r=e.name(),s=t(r);for(const i of e.project().uiSourceCodes())n===i.parentURL()&&t(i.name())===s&&o.push(i.name());o.sort(c.StringUtilities.naturalOrderComparator);const a=c.NumberUtilities.mod(o.indexOf(r)+1,o.length),l=i.ParsedURL.ParsedURL.concatenate(n?i.ParsedURL.ParsedURL.concatenate(n,"/"):"",o[a]),d=e.project().uiSourceCodeForURL(l);return d!==e?d:null}handleAction(e,i){const o=t.Context.Context.instance().flavor(Ri);if(!o)return!1;const n=o.currentUISourceCode();if(!n)return!1;const r=_i.nextFile(n);return!!r&&(o.showSourceLocation(r),!0)}}class zi{static instance(e={forceNew:null}){const{forceNew:t}=e;return Hi&&!t||(Hi=new zi),Hi}handleAction(e,i){const o=t.Context.Context.instance().flavor(Ri);if(!o)return!1;switch(i){case"sources.close-all":return o.editorContainer.closeAllFiles(),!0;case"sources.jump-to-previous-location":return o.onJumpToPreviousLocation(),!0;case"sources.jump-to-next-location":return o.onJumpToNextLocation(),!0;case"sources.next-editor-tab":return o.editorContainer.selectNextTab(),!0;case"sources.previous-editor-tab":return o.editorContainer.selectPrevTab(),!0;case"sources.close-editor-tab":return o.onCloseEditorTab();case"sources.go-to-line":return o.showGoToLineQuickOpen(),!0;case"sources.go-to-member":return o.showOutlineQuickOpen(),!0;case"sources.save":return o.save(),!0;case"sources.save-all":return o.saveAll(),!0}return!1}}const qi=".headers";var Gi;!function(e){e.ImageView="ImageView",e.FontView="FontView",e.HeadersView="HeadersView",e.SourceView="SourceView"}(Gi||(Gi={}));var $i=Object.freeze({__proto__:null,SourcesView:Ri,get Events(){return Bi},registerEditorAction:Oi,getRegisteredEditorActions:Wi,SwitchFileActionDelegate:_i,ActionDelegate:zi});const Ki=new CSSStyleSheet;Ki.replaceSync(".thread-item{padding:3px 8px 3px 20px;position:relative;min-height:18px;line-height:15px;display:flex;flex-wrap:wrap}.thread-item + .thread-item{border-top:1px solid var(--color-details-hairline-light)}.thread-item:hover{background-color:var(--color-background-elevation-1)}.thread-item:focus-visible{background-color:var(--legacy-focus-bg-color)}.thread-item-title,\n.thread-item-paused-state{text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.thread-item-paused-state{color:var(--color-text-disabled);margin-left:auto;padding:0 10px}.selected-thread-icon{display:none;position:absolute;top:3px;left:4px}.thread-item.selected .selected-thread-icon{display:block}@media (forced-colors: active){.thread-item:hover,\n  .thread-item:focus-visible{forced-color-adjust:none;background-color:Highlight}.thread-item:hover > div,\n  .thread-item:focus-visible > div{color:HighlightText}}\n/*# sourceURL=threadsSidebarPane.css */\n");const Ji={paused:"paused"},Yi=e.i18n.registerUIStrings("panels/sources/ThreadsSidebarPane.ts",Ji),Xi=e.i18n.getLocalizedString.bind(void 0,Yi);let Qi;class Zi extends t.Widget.VBox{items;list;selectedModel;constructor(){super(!0),this.items=new t.ListModel.ListModel,this.list=new t.ListControl.ListControl(this.items,this,t.ListControl.ListMode.NonViewport);const e=t.Context.Context.instance().flavor(o.Target.Target);this.selectedModel=null!==e?e.model(o.DebuggerModel.DebuggerModel):null,this.contentElement.appendChild(this.list.element),t.Context.Context.instance().addFlavorChangeListener(o.Target.Target,this.targetFlavorChanged,this),o.TargetManager.TargetManager.instance().observeModels(o.DebuggerModel.DebuggerModel,this)}static instance(){return Qi||(Qi=new Zi),Qi}static shouldBeShown(){return o.TargetManager.TargetManager.instance().models(o.DebuggerModel.DebuggerModel).length>=2}createElementForItem(e){const i=document.createElement("div");i.classList.add("thread-item");const n=i.createChild("div","thread-item-title"),s=i.createChild("div","thread-item-paused-state"),a=new r.Icon.Icon;a.data={iconName:"large-arrow-right-filled",color:"var(--icon-arrow-main-thread)",width:"14px",height:"14px"},a.classList.add("selected-thread-icon"),i.appendChild(a),i.tabIndex=-1,self.onInvokeElement(i,(i=>{t.Context.Context.instance().setFlavor(o.Target.Target,e.target()),i.consume(!0)}));const c=t.Context.Context.instance().flavor(o.Target.Target)===e.target();function l(){const t=e.runtimeModel().defaultExecutionContext();n.textContent=t&&t.label()?t.label():e.target().name()}function d(){s.textContent=e.isPaused()?Xi(Ji.paused):""}return i.classList.toggle("selected",c),t.ARIAUtils.setSelected(i,c),e.addEventListener(o.DebuggerModel.Events.DebuggerPaused,d),e.addEventListener(o.DebuggerModel.Events.DebuggerResumed,d),e.runtimeModel().addEventListener(o.RuntimeModel.Events.ExecutionContextChanged,l),o.TargetManager.TargetManager.instance().addEventListener(o.TargetManager.Events.NameChanged,(function(t){t.data===e.target()&&l()})),d(),l(),i}heightForItem(e){return console.assert(!1),0}isItemSelectable(e){return!0}selectedItemChanged(e,t,i,o){i&&(i.tabIndex=-1);const n=o;n&&(this.setDefaultFocusedElement(n),n.tabIndex=0,this.hasFocus()&&n.focus())}updateSelectedItemARIA(e,t){return!1}modelAdded(e){this.items.insert(this.items.length,e);t.Context.Context.instance().flavor(o.Target.Target)===e.target()&&this.list.selectItem(e)}modelRemoved(e){this.items.remove(this.items.indexOf(e))}targetFlavorChanged({data:e}){const t=this.hasFocus(),i=e.model(o.DebuggerModel.DebuggerModel);this.list.selectItem(i),i&&this.list.refreshItem(i),null!==this.selectedModel&&this.list.refreshItem(this.selectedModel),this.selectedModel=i,t&&this.focus()}wasShown(){super.wasShown(),this.registerCSSFiles([Ki])}}var eo=Object.freeze({__proto__:null,ThreadsSidebarPane:Zi});const to={dropWorkspaceFolderHere:"Drop workspace folder here",moreOptions:"More options",showNavigator:"Show navigator",hideNavigator:"Hide navigator",navigatorShown:"Navigator sidebar shown",navigatorHidden:"Navigator sidebar hidden",debuggerShown:"Debugger sidebar shown",debuggerHidden:"Debugger sidebar hidden",showDebugger:"Show debugger",hideDebugger:"Hide debugger",groupByFolder:"Group by folder",groupByAuthored:"Group by Authored/Deployed",hideIgnoreListed:"Hide ignore-listed sources",resumeWithAllPausesBlockedForMs:"Resume with all pauses blocked for 500 ms",terminateCurrentJavascriptCall:"Terminate current JavaScript call",pauseOnCaughtExceptions:"Pause on caught exceptions",revealInSidebar:"Reveal in sidebar",continueToHere:"Continue to here",storeSAsGlobalVariable:"Store {PH1} as global variable",copyS:"Copy {PH1}",copyStringContents:"Copy string contents",copyStringAsJSLiteral:"Copy string as JavaScript literal",copyStringAsJSONLiteral:"Copy string as JSON literal",showFunctionDefinition:"Show function definition",openInSourcesPanel:"Open in Sources panel"},io=e.i18n.registerUIStrings("panels/sources/SourcesPanel.ts",to),oo=e.i18n.getLocalizedString.bind(void 0,io),no=new Set(["number","boolean","bigint","undefined"]);let ro,so;class ao extends t.Panel.Panel{workspace;togglePauseAction;stepOverAction;stepIntoAction;stepOutAction;stepAction;toggleBreakpointsActiveAction;debugToolbar;debugToolbarDrawer;debuggerPausedMessage;splitWidget;editorView;navigatorTabbedLocation;sourcesViewInternal;toggleNavigatorSidebarButton;toggleDebuggerSidebarButton;threadsSidebarPane;watchSidebarPane;callstackPane;liveLocationPool;lastModificationTime;pausedInternal;switchToPausedTargetTimeout;ignoreExecutionLineEvents;executionLineLocation;pauseOnExceptionButton;sidebarPaneStack;tabbedLocationHeader;extensionSidebarPanesContainer;sidebarPaneView;constructor(){super("sources"),I.Runtime.Runtime.isDescriptorEnabled({experiment:void 0,condition:I.Runtime.ConditionName.NOT_SOURCES_HIDE_ADD_FOLDER})&&new t.DropTarget.DropTarget(this.element,[t.DropTarget.Type.Folder],oo(to.dropWorkspaceFolderHere),this.handleDrop.bind(this)),this.workspace=v.Workspace.WorkspaceImpl.instance(),this.togglePauseAction=t.ActionRegistry.ActionRegistry.instance().action("debugger.toggle-pause"),this.stepOverAction=t.ActionRegistry.ActionRegistry.instance().action("debugger.step-over"),this.stepIntoAction=t.ActionRegistry.ActionRegistry.instance().action("debugger.step-into"),this.stepOutAction=t.ActionRegistry.ActionRegistry.instance().action("debugger.step-out"),this.stepAction=t.ActionRegistry.ActionRegistry.instance().action("debugger.step"),this.toggleBreakpointsActiveAction=t.ActionRegistry.ActionRegistry.instance().action("debugger.toggle-breakpoints-active"),this.debugToolbar=this.createDebugToolbar(),this.debugToolbarDrawer=this.createDebugToolbarDrawer(),this.debuggerPausedMessage=new je;this.splitWidget=new t.SplitWidget.SplitWidget(!0,!0,"sourcesPanelSplitViewState",225),this.splitWidget.enableShowModeSaving(),this.splitWidget.show(this.element);this.editorView=new t.SplitWidget.SplitWidget(!0,!1,"sourcesPanelNavigatorSplitViewState",225),this.editorView.enableShowModeSaving(),this.splitWidget.setMainWidget(this.editorView),this.navigatorTabbedLocation=t.ViewManager.ViewManager.instance().createTabbedLocation(this.revealNavigatorSidebar.bind(this),"navigator-view",!0);const e=this.navigatorTabbedLocation.tabbedPane();e.setMinimumSize(100,25),e.element.classList.add("navigator-tabbed-pane");const n=new t.Toolbar.ToolbarMenuButton(this.populateNavigatorMenu.bind(this),!0);if(n.setTitle(oo(to.moreOptions)),e.rightToolbar().appendToolbarItem(n),e.addEventListener(t.TabbedPane.Events.TabSelected,(({data:{tabId:e}})=>a.userMetrics.sourcesSidebarTabShown(e))),t.ViewManager.ViewManager.instance().hasViewsForLocation("run-view-sidebar")){const i=new t.SplitWidget.SplitWidget(!1,!0,"sourcePanelNavigatorSidebarSplitViewState");i.setMainWidget(e);const o=t.ViewManager.ViewManager.instance().createTabbedLocation(this.revealNavigatorSidebar.bind(this),"run-view-sidebar").tabbedPane();i.setSidebarWidget(o),i.installResizer(o.headerElement()),this.editorView.setSidebarWidget(i)}else this.editorView.setSidebarWidget(e);this.sourcesViewInternal=new Ri,this.sourcesViewInternal.addEventListener(Bi.EditorSelected,this.editorSelected.bind(this)),this.toggleNavigatorSidebarButton=this.editorView.createShowHideSidebarButton(oo(to.showNavigator),oo(to.hideNavigator),oo(to.navigatorShown),oo(to.navigatorHidden)),this.toggleDebuggerSidebarButton=this.splitWidget.createShowHideSidebarButton(oo(to.showDebugger),oo(to.hideDebugger),oo(to.debuggerShown),oo(to.debuggerHidden)),this.editorView.setMainWidget(this.sourcesViewInternal),this.threadsSidebarPane=null,this.watchSidebarPane=t.ViewManager.ViewManager.instance().view("sources.watch"),this.callstackPane=X.instance(),i.Settings.Settings.instance().moduleSetting("sidebarPosition").addChangeListener(this.updateSidebarPosition.bind(this)),this.updateSidebarPosition(),this.updateDebuggerButtonsAndStatus(),this.liveLocationPool=new d.LiveLocation.LiveLocationPool,this.setTarget(t.Context.Context.instance().flavor(o.Target.Target)),i.Settings.Settings.instance().moduleSetting("breakpointsActive").addChangeListener(this.breakpointsActiveStateChanged,this),t.Context.Context.instance().addFlavorChangeListener(o.Target.Target,this.onCurrentTargetChanged,this),t.Context.Context.instance().addFlavorChangeListener(o.DebuggerModel.CallFrame,this.callFrameChanged,this),o.TargetManager.TargetManager.instance().addModelListener(o.DebuggerModel.DebuggerModel,o.DebuggerModel.Events.DebuggerWasEnabled,this.debuggerWasEnabled,this),o.TargetManager.TargetManager.instance().addModelListener(o.DebuggerModel.DebuggerModel,o.DebuggerModel.Events.DebuggerPaused,this.debuggerPaused,this),o.TargetManager.TargetManager.instance().addModelListener(o.DebuggerModel.DebuggerModel,o.DebuggerModel.Events.DebugInfoAttached,this.debugInfoAttached,this),o.TargetManager.TargetManager.instance().addModelListener(o.DebuggerModel.DebuggerModel,o.DebuggerModel.Events.DebuggerResumed,(e=>this.debuggerResumed(e.data))),o.TargetManager.TargetManager.instance().addModelListener(o.DebuggerModel.DebuggerModel,o.DebuggerModel.Events.GlobalObjectCleared,(e=>this.debuggerResumed(e.data))),x.ExtensionServer.ExtensionServer.instance().addEventListener(x.ExtensionServer.Events.SidebarPaneAdded,this.extensionSidebarPaneAdded,this),o.TargetManager.TargetManager.instance().observeTargets(this),this.lastModificationTime=-1/0}static instance(e={forceNew:null}){const{forceNew:t}=e;return ro&&!t||(ro=new ao),ro}static updateResizerAndSidebarButtons(e){e.sourcesViewInternal.leftToolbar().removeToolbarItems(),e.sourcesViewInternal.rightToolbar().removeToolbarItems(),e.sourcesViewInternal.bottomToolbar().removeToolbarItems();const i=xo.isShowing()&&!t.InspectorView.InspectorView.instance().isDrawerMinimized();e.splitWidget.isVertical()||i?e.splitWidget.uninstallResizer(e.sourcesViewInternal.toolbarContainerElement()):e.splitWidget.installResizer(e.sourcesViewInternal.toolbarContainerElement()),i||(e.sourcesViewInternal.leftToolbar().appendToolbarItem(e.toggleNavigatorSidebarButton),e.splitWidget.isVertical()?e.sourcesViewInternal.rightToolbar().appendToolbarItem(e.toggleDebuggerSidebarButton):e.sourcesViewInternal.bottomToolbar().appendToolbarItem(e.toggleDebuggerSidebarButton))}targetAdded(e){this.showThreadsIfNeeded()}targetRemoved(e){}showThreadsIfNeeded(){Zi.shouldBeShown()&&!this.threadsSidebarPane&&(this.threadsSidebarPane=t.ViewManager.ViewManager.instance().view("sources.threads"),this.sidebarPaneStack&&this.threadsSidebarPane&&this.sidebarPaneStack.appendView(this.threadsSidebarPane,this.splitWidget.isVertical()?this.watchSidebarPane:this.callstackPane))}setTarget(e){if(!e)return;const t=e.model(o.DebuggerModel.DebuggerModel);t&&(t.isPaused()?this.showDebuggerPausedDetails(t.debuggerPausedDetails()):(this.pausedInternal=!1,this.clearInterface(),this.toggleDebuggerSidebarButton.setEnabled(!0)))}onCurrentTargetChanged({data:e}){this.setTarget(e)}paused(){return this.pausedInternal||!1}wasShown(){t.Context.Context.instance().setFlavor(ao,this),this.registerCSSFiles([ze]),super.wasShown();const e=xo.instance();e&&e.isShowing()&&(t.InspectorView.InspectorView.instance().setDrawerMinimized(!0),ao.updateResizerAndSidebarButtons(this)),this.editorView.setMainWidget(this.sourcesViewInternal)}willHide(){super.willHide(),t.Context.Context.instance().setFlavor(ao,null),xo.isShowing()&&(xo.instance().showViewInWrapper(),t.InspectorView.InspectorView.instance().setDrawerMinimized(!1),ao.updateResizerAndSidebarButtons(this))}resolveLocation(e){return"sources.sidebar-top"===e||"sources.sidebar-bottom"===e||"sources.sidebar-tabs"===e?this.sidebarPaneStack||null:this.navigatorTabbedLocation}ensureSourcesViewVisible(){return!!xo.isShowing()||!!t.InspectorView.InspectorView.instance().canSelectPanel("sources")&&(t.ViewManager.ViewManager.instance().showView("sources"),!0)}onResize(){"auto"===i.Settings.Settings.instance().moduleSetting("sidebarPosition").get()&&this.element.window().requestAnimationFrame(this.updateSidebarPosition.bind(this))}searchableView(){return this.sourcesViewInternal.searchableView()}toggleNavigatorSidebar(){this.editorView.toggleSidebar()}toggleDebuggerSidebar(){this.splitWidget.toggleSidebar()}debuggerPaused(e){const n=e.data,r=n.debuggerPausedDetails();!this.pausedInternal&&i.Settings.Settings.instance().moduleSetting("autoFocusOnDebuggerPausedEnabled").get()&&this.setAsCurrentPanel(),t.Context.Context.instance().flavor(o.Target.Target)===n.target()?this.showDebuggerPausedDetails(r):this.pausedInternal||t.Context.Context.instance().setFlavor(o.Target.Target,n.target())}debugInfoAttached(e){const{debuggerModel:i}=e.data;if(!i.isPaused())return;const n=i.debuggerPausedDetails();n&&t.Context.Context.instance().flavor(o.Target.Target)===i.target()&&this.showDebuggerPausedDetails(n)}showDebuggerPausedDetails(e){this.pausedInternal=!0,this.updateDebuggerButtonsAndStatus(),t.Context.Context.instance().setFlavor(o.DebuggerModel.DebuggerPausedDetails,e),this.toggleDebuggerSidebarButton.setEnabled(!1),this.revealDebuggerSidebar(),window.focus(),a.InspectorFrontendHost.InspectorFrontendHostInstance.bringToFront()}debuggerResumed(e){const i=e.target();t.Context.Context.instance().flavor(o.Target.Target)===i&&(this.pausedInternal=!1,this.clearInterface(),this.toggleDebuggerSidebarButton.setEnabled(!0),this.switchToPausedTargetTimeout=window.setTimeout(this.switchToPausedTarget.bind(this,e),500))}debuggerWasEnabled(e){const i=e.data;t.Context.Context.instance().flavor(o.Target.Target)===i.target()&&this.updateDebuggerButtonsAndStatus()}get visibleView(){return this.sourcesViewInternal.visibleView()}showUISourceCode(e,t,i,o){if(o){const e=xo.isShowing();if(!this.isShowing()&&!e)return}else this.showEditor();this.sourcesViewInternal.showSourceLocation(e,void 0===t?void 0:{lineNumber:t,columnNumber:i},o)}showEditor(){xo.isShowing()||this.setAsCurrentPanel()}showUILocation(e,t){this.showUISourceCode(e.uiSourceCode,e.lineNumber,e.columnNumber,t)}revealInNavigator(e,i){for(const o of yo){const n=o.navigatorView(),r=o.viewId;r&&n.acceptProject(e.project())&&(n.revealUISourceCode(e,!0),i?this.navigatorTabbedLocation.tabbedPane().selectTab(r):t.ViewManager.ViewManager.instance().showView(r))}}addExperimentMenuItem(e,t,o){const n=new r.Icon.Icon;n.data={iconName:"experiment",color:"var(--icon-default)",width:"16px"},n.style.minHeight="16px",n.style.minWidth="16px",e.appendCheckboxItem(o,(function(){const e=I.Runtime.experiments.isEnabled(t);I.Runtime.experiments.setEnabled(t,!e),a.userMetrics.experimentChanged(t,e);const o=i.Settings.Settings.instance().moduleSetting("navigatorGroupByFolder");o.set(o.get())}),I.Runtime.experiments.isEnabled(t),!1,n)}populateNavigatorMenu(e){const t=i.Settings.Settings.instance().moduleSetting("navigatorGroupByFolder");e.appendItemsAtLocation("navigatorMenu"),e.viewSection().appendCheckboxItem(oo(to.groupByFolder),(()=>t.set(!t.get())),t.get()),this.addExperimentMenuItem(e.viewSection(),I.Runtime.ExperimentName.AUTHORED_DEPLOYED_GROUPING,oo(to.groupByAuthored)),this.addExperimentMenuItem(e.viewSection(),I.Runtime.ExperimentName.JUST_MY_CODE,oo(to.hideIgnoreListed))}setIgnoreExecutionLineEvents(e){this.ignoreExecutionLineEvents=e}updateLastModificationTime(){this.lastModificationTime=window.performance.now()}async executionLineChanged(e){const t=await e.uiLocation();e.isDisposed()||t&&(window.performance.now()-this.lastModificationTime<co||this.sourcesViewInternal.showSourceLocation(t.uiSourceCode,t,void 0,!0))}lastModificationTimeoutPassedForTest(){co=Number.MIN_VALUE}updateLastModificationTimeForTest(){co=Number.MAX_VALUE}async callFrameChanged(){const e=t.Context.Context.instance().flavor(o.DebuggerModel.CallFrame);e&&(this.executionLineLocation&&this.executionLineLocation.dispose(),this.executionLineLocation=await d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().createCallFrameLiveLocation(e.location(),this.executionLineChanged.bind(this),this.liveLocationPool))}async updateDebuggerButtonsAndStatus(){const e=t.Context.Context.instance().flavor(o.Target.Target),i=e?e.model(o.DebuggerModel.DebuggerModel):null;i?this.pausedInternal?(this.togglePauseAction.setToggled(!0),this.togglePauseAction.setEnabled(!0),this.stepOverAction.setEnabled(!0),this.stepIntoAction.setEnabled(!0),this.stepOutAction.setEnabled(!0),this.stepAction.setEnabled(!0)):(this.togglePauseAction.setToggled(!1),this.togglePauseAction.setEnabled(!i.isPausing()),this.stepOverAction.setEnabled(!1),this.stepIntoAction.setEnabled(!1),this.stepOutAction.setEnabled(!1),this.stepAction.setEnabled(!1)):(this.togglePauseAction.setEnabled(!1),this.stepOverAction.setEnabled(!1),this.stepIntoAction.setEnabled(!1),this.stepOutAction.setEnabled(!1),this.stepAction.setEnabled(!1));const n=i?i.debuggerPausedDetails():null;await this.debuggerPausedMessage.render(n,d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance(),f.BreakpointManager.BreakpointManager.instance()),n&&this.updateDebuggerButtonsAndStatusForTest()}updateDebuggerButtonsAndStatusForTest(){}clearInterface(){this.updateDebuggerButtonsAndStatus(),t.Context.Context.instance().setFlavor(o.DebuggerModel.DebuggerPausedDetails,null),this.switchToPausedTargetTimeout&&clearTimeout(this.switchToPausedTargetTimeout),this.liveLocationPool.disposeAll()}switchToPausedTarget(e){if(delete this.switchToPausedTargetTimeout,!this.pausedInternal&&!e.isPaused())for(const e of o.TargetManager.TargetManager.instance().models(o.DebuggerModel.DebuggerModel))if(e.isPaused()){t.Context.Context.instance().setFlavor(o.Target.Target,e.target());break}}runSnippet(){const e=this.sourcesViewInternal.currentUISourceCode();e&&y.ScriptSnippetFileSystem.evaluateScriptSnippet(e)}editorSelected(e){const t=e.data;this.editorView.mainWidget()&&i.Settings.Settings.instance().moduleSetting("autoRevealInNavigator").get()&&this.revealInNavigator(t,!0)}togglePause(){const e=t.Context.Context.instance().flavor(o.Target.Target);if(!e)return!0;const i=e.model(o.DebuggerModel.DebuggerModel);return!i||(this.pausedInternal?(this.pausedInternal=!1,i.resume()):i.pause(),this.clearInterface(),!0)}prepareToResume(){if(!this.pausedInternal)return null;this.pausedInternal=!1,this.clearInterface();const e=t.Context.Context.instance().flavor(o.Target.Target);return e?e.model(o.DebuggerModel.DebuggerModel):null}longResume(){const e=this.prepareToResume();e&&(e.skipAllPausesUntilReloadOrTimeout(500),e.resume())}terminateExecution(){const e=this.prepareToResume();e&&(e.runtimeModel().terminateExecution(),e.resume())}stepOver(){const e=this.prepareToResume();return e&&e.stepOver(),!0}stepInto(){const e=this.prepareToResume();return e&&e.stepInto(),!0}stepIntoAsync(){const e=this.prepareToResume();return e&&e.scheduleStepIntoAsync(),!0}stepOut(){const e=this.prepareToResume();return e&&e.stepOut(),!0}async continueToLocation(e){const i=t.Context.Context.instance().flavor(o.RuntimeModel.ExecutionContext);if(!i)return;const n=(await d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().uiLocationToRawLocations(e.uiSourceCode,e.lineNumber,0)).find((e=>e.debuggerModel===i.debuggerModel));n&&this.prepareToResume()&&n.continueToLocation()}toggleBreakpointsActive(){i.Settings.Settings.instance().moduleSetting("breakpointsActive").set(!i.Settings.Settings.instance().moduleSetting("breakpointsActive").get())}breakpointsActiveStateChanged(){const e=i.Settings.Settings.instance().moduleSetting("breakpointsActive").get();this.toggleBreakpointsActiveAction.setToggled(!e),this.sourcesViewInternal.toggleBreakpointsActiveState(e)}createDebugToolbar(){const e=new t.Toolbar.Toolbar("scripts-debug-toolbar"),i=new t.Toolbar.ToolbarButton(oo(to.resumeWithAllPausesBlockedForMs),"play");i.addEventListener(t.Toolbar.ToolbarButton.Events.Click,this.longResume,this);const o=new t.Toolbar.ToolbarButton(oo(to.terminateCurrentJavascriptCall),"stop");return o.addEventListener(t.Toolbar.ToolbarButton.Events.Click,this.terminateExecution,this),e.appendToolbarItem(t.Toolbar.Toolbar.createLongPressActionButton(this.togglePauseAction,[o,i],[])),e.appendToolbarItem(t.Toolbar.Toolbar.createActionButton(this.stepOverAction)),e.appendToolbarItem(t.Toolbar.Toolbar.createActionButton(this.stepIntoAction)),e.appendToolbarItem(t.Toolbar.Toolbar.createActionButton(this.stepOutAction)),e.appendToolbarItem(t.Toolbar.Toolbar.createActionButton(this.stepAction)),e.appendSeparator(),e.appendToolbarItem(t.Toolbar.Toolbar.createActionButton(this.toggleBreakpointsActiveAction)),e}createDebugToolbarDrawer(){const e=document.createElement("div");e.classList.add("scripts-debug-toolbar-drawer");const o=oo(to.pauseOnCaughtExceptions),n=i.Settings.Settings.instance().moduleSetting("pauseOnCaughtException");return e.appendChild(t.SettingsUI.createSettingCheckbox(o,n,!0)),e}appendApplicableItems(e,t,i){this.appendUISourceCodeItems(e,t,i),this.appendUISourceCodeFrameItems(e,t,i),this.appendUILocationItems(t,i),this.appendRemoteObjectItems(t,i),this.appendNetworkRequestItems(t,i)}appendUISourceCodeItems(e,t,i){if(!(i instanceof v.UISourceCode.UISourceCode&&e.target))return;const o=i,n=e.target;o.project().isServiceProject()||n.isSelfOrDescendant(this.navigatorTabbedLocation.widget().element)||I.Runtime.experiments.isEnabled(I.Runtime.ExperimentName.JUST_MY_CODE)&&d.IgnoreListManager.IgnoreListManager.instance().isUserOrSourceMapIgnoreListedUISourceCode(o)||t.revealSection().appendItem(oo(to.revealInSidebar),this.handleContextMenuReveal.bind(this,o)),o.contentType().hasScripts()&&d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().scriptsForUISourceCode(o).every((e=>e.isJavaScript()))&&this.callstackPane.appendIgnoreListURLContextMenuItems(t,o)}appendUISourceCodeFrameItems(e,t,i){i instanceof si&&(i.uiSourceCode().contentType().isFromSourceMap()||i.textEditor.state.selection.main.empty||t.debugSection().appendAction("debugger.evaluate-selection"))}appendUILocationItems(e,i){if(!(i instanceof v.UISourceCode.UILocation))return;const n=i,r=n.uiSourceCode;if(!d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().scriptsForUISourceCode(r).every((e=>e.isJavaScript())))return;if(r.contentType().hasScripts()){const i=t.Context.Context.instance().flavor(o.Target.Target),s=i?i.model(o.DebuggerModel.DebuggerModel):null;s&&s.isPaused()&&e.debugSection().appendItem(oo(to.continueToHere),this.continueToLocation.bind(this,n)),this.callstackPane.appendIgnoreListURLContextMenuItems(e,r)}}handleContextMenuReveal(e){this.editorView.showBoth(),this.revealInNavigator(e)}appendRemoteObjectItems(e,n){if(!(n instanceof o.RemoteObject.RemoteObject))return;const r=i.Settings.Settings.instance().moduleSetting("textEditorIndent").get(),s=n,l=t.Context.Context.instance().flavor(o.RuntimeModel.ExecutionContext);const d="wasm"===s.type?s.subtype:"node"===s.subtype?"outerHTML":s.type;e.debugSection().appendItem(oo(to.storeSAsGlobalVariable,{PH1:String(d)}),(()=>l?.target().model(o.ConsoleModel.ConsoleModel)?.saveToTempVariable(l,s)));const u=e.clipboardSection(),h=a.InspectorFrontendHost.InspectorFrontendHostInstance;if("string"===s.type)u.appendItem(oo(to.copyStringContents),(()=>{h.copyText(s.value)})),u.appendItem(oo(to.copyStringAsJSLiteral),(()=>{h.copyText(c.StringUtilities.formatAsJSLiteral(s.value))})),u.appendItem(oo(to.copyStringAsJSONLiteral),(()=>{h.copyText(JSON.stringify(s.value))}));else if(no.has(s.type))u.appendItem(oo(to.copyS,{PH1:String(d)}),(()=>{h.copyText(s.description)}));else if("object"===s.type){const e=async()=>{const e=await s.callFunctionJSON(p,[{value:{subtype:s.subtype,indent:r}}]);h.copyText(e)};u.appendItem(oo(to.copyS,{PH1:String(d)}),e)}else"function"===s.type&&e.debugSection().appendItem(oo(to.showFunctionDefinition),this.showFunctionDefinition.bind(this,s));function p(e){const t=e.subtype,i=e.indent;if("node"===t)return this instanceof Element?this.outerHTML:void 0;if(t&&void 0===this)return String(t);try{return JSON.stringify(this,null,i)}catch(e){return String(this)}}}appendNetworkRequestItems(e,t){if(!(t instanceof o.NetworkRequest.NetworkRequest))return;const i=t,n=this.workspace.uiSourceCodeForURL(i.url());if(!n)return;const r=oo(to.openInSourcesPanel),s=this.showUILocation.bind(this,n.uiLocation(0,0));e.revealSection().appendItem(r,s)}showFunctionDefinition(e){o.RemoteObject.RemoteFunction.objectAsFunction(e).targetFunction().then((e=>e.debuggerModel().functionDetailsPromise(e).then(this.didGetFunctionDetails.bind(this))))}async didGetFunctionDetails(e){if(!e||!e.location)return;const t=await d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().rawLocationToUILocation(e.location);t&&this.showUILocation(t)}revealNavigatorSidebar(){this.setAsCurrentPanel(),this.editorView.showBoth(!0)}revealDebuggerSidebar(){i.Settings.Settings.instance().moduleSetting("autoFocusOnDebuggerPausedEnabled").get()&&(this.setAsCurrentPanel(),this.splitWidget.showBoth(!0))}updateSidebarPosition(){let e;const o=i.Settings.Settings.instance().moduleSetting("sidebarPosition").get();if(e="right"!==o&&("bottom"===o||t.InspectorView.InspectorView.instance().element.offsetWidth<680),this.sidebarPaneView&&e===!this.splitWidget.isVertical())return;if(this.sidebarPaneView&&this.sidebarPaneView.shouldHideOnDetach())return;this.sidebarPaneView&&this.sidebarPaneView.detach(),this.splitWidget.setVertical(!e),this.splitWidget.element.classList.toggle("sources-split-view-vertical",e),ao.updateResizerAndSidebarButtons(this);const n=new t.Widget.VBox;n.element.appendChild(this.debugToolbar.element),n.element.appendChild(this.debugToolbarDrawer),n.setMinimumAndPreferredSizes(lo,25,lo,100),this.sidebarPaneStack=t.ViewManager.ViewManager.instance().createStackLocation(this.revealDebuggerSidebar.bind(this)),this.sidebarPaneStack.widget().element.classList.add("overflow-auto"),this.sidebarPaneStack.widget().show(n.element),this.sidebarPaneStack.widget().element.appendChild(this.debuggerPausedMessage.element()),this.sidebarPaneStack.appendApplicableItems("sources.sidebar-top"),this.threadsSidebarPane&&this.sidebarPaneStack.appendView(this.threadsSidebarPane);const r=t.ViewManager.ViewManager.instance().view("sources.jsBreakpoints"),s=t.ViewManager.ViewManager.instance().view("sources.scopeChain");if(this.tabbedLocationHeader&&(this.splitWidget.uninstallResizer(this.tabbedLocationHeader),this.tabbedLocationHeader=null),e){const e=new t.SplitWidget.SplitWidget(!0,!0,"sourcesPanelDebuggerSidebarSplitViewState",.5);e.setMainWidget(n),this.sidebarPaneStack.showView(r),this.sidebarPaneStack.showView(this.callstackPane);const i=t.ViewManager.ViewManager.instance().createTabbedLocation(this.revealDebuggerSidebar.bind(this));e.setSidebarWidget(i.tabbedPane()),this.tabbedLocationHeader=i.tabbedPane().headerElement(),this.splitWidget.installResizer(this.tabbedLocationHeader),this.splitWidget.installResizer(this.debugToolbar.gripElementForResize()),i.appendView(s),i.appendView(this.watchSidebarPane),i.appendApplicableItems("sources.sidebar-tabs"),this.extensionSidebarPanesContainer=i,this.sidebarPaneView=e}else this.sidebarPaneStack.appendView(this.watchSidebarPane),this.sidebarPaneStack.showView(r),this.sidebarPaneStack.showView(s),this.sidebarPaneStack.showView(this.callstackPane),this.extensionSidebarPanesContainer=this.sidebarPaneStack,this.sidebarPaneView=n,this.splitWidget.uninstallResizer(this.debugToolbar.gripElementForResize());this.sidebarPaneStack.appendApplicableItems("sources.sidebar-bottom");const a=x.ExtensionServer.ExtensionServer.instance().sidebarPanes();for(let e=0;e<a.length;++e)this.addExtensionSidebarPane(a[e]);this.splitWidget.setSidebarWidget(this.sidebarPaneView)}setAsCurrentPanel(){return t.ViewManager.ViewManager.instance().showView("sources")}extensionSidebarPaneAdded(e){this.addExtensionSidebarPane(e.data)}addExtensionSidebarPane(e){e.panelName()===this.name&&this.extensionSidebarPanesContainer.appendView(e)}sourcesView(){return this.sourcesViewInternal}handleDrop(e){const t=e.items;if(!t.length)return;const i=t[0].webkitGetAsEntry();i&&i.isDirectory&&a.InspectorFrontendHost.InspectorFrontendHostInstance.upgradeDraggedFileSystemPermissions(i.filesystem)}}let co=200;const lo=215;let uo,ho,po,go,mo,bo;class fo{static instance(e={forceNew:null}){const{forceNew:t}=e;return uo&&!t||(uo=new fo),uo}async reveal(e,t){if(!(e instanceof v.UISourceCode.UILocation))throw new Error("Internal error: not a ui location");ao.instance().showUILocation(e,t)}}class So{static instance(e={forceNew:null}){const{forceNew:t}=e;return ho&&!t||(ho=new So),ho}async reveal(e,t){if(!(e instanceof o.DebuggerModel.Location))throw new Error("Internal error: not a debugger location");const i=await d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().rawLocationToUILocation(e);i&&ao.instance().showUILocation(i,t)}}class vo{static instance(e={forceNew:null}){const{forceNew:t}=e;return po&&!t||(po=new vo),po}async reveal(e,t){if(!(e instanceof v.UISourceCode.UISourceCode))throw new Error("Internal error: not a ui source code");ao.instance().showUISourceCode(e,void 0,void 0,t)}}class Co{static instance(e={forceNew:null}){const{forceNew:t}=e;return go&&!t||(go=new Co),go}async reveal(e){if(i.Settings.Settings.instance().moduleSetting("autoFocusOnDebuggerPausedEnabled").get())return ao.instance().setAsCurrentPanel()}}class wo{static instance(e={forceNew:null}){const{forceNew:t}=e;return mo&&!t||(mo=new wo),mo}handleAction(e,o){const n=ao.instance();if(!n.ensureSourcesViewVisible())return!1;if("debugger.toggle-pause"===o){return e.flavor(t.ShortcutRegistry.ForwardedShortcut)&&!i.Settings.Settings.instance().moduleSetting("disablePausedStateOverlay").get()||n.togglePause(),!0}return!1}}class Io{static instance(e={forceNew:null}){const{forceNew:t}=e;return bo&&!t||(bo=new Io),bo}handleAction(e,i){const n=ao.instance();switch(i){case"debugger.step-over":return n.stepOver(),!0;case"debugger.step-into":return n.stepIntoAsync(),!0;case"debugger.step":return n.stepInto(),!0;case"debugger.step-out":return n.stepOut(),!0;case"debugger.run-snippet":return n.runSnippet(),!0;case"debugger.toggle-breakpoints-active":return n.toggleBreakpointsActive(),!0;case"debugger.evaluate-selection":{const e=t.Context.Context.instance().flavor(si);if(e){const{state:i}=e.textEditor;let n=i.sliceDoc(i.selection.main.from,i.selection.main.to);const r=t.Context.Context.instance().flavor(o.RuntimeModel.ExecutionContext),s=r?.target().model(o.ConsoleModel.ConsoleModel);if(r&&s){const e=s.addCommandMessage(r,n);n=C.JavaScriptREPL.JavaScriptREPL.wrapObjectLiteral(n),s.evaluateCommandInConsole(r,e,n,!0)}}return!0}case"sources.toggle-navigator-sidebar":return n.toggleNavigatorSidebar(),!0;case"sources.toggle-debugger-sidebar":return n.toggleDebuggerSidebar(),!0}return!1}}class xo extends t.Widget.VBox{view;constructor(){super(),this.element.classList.add("sources-view-wrapper"),this.view=ao.instance().sourcesView()}static instance(){return so||(so=new xo),so}static isShowing(){return Boolean(so)&&so.isShowing()}wasShown(){ao.instance().isShowing()?t.InspectorView.InspectorView.instance().setDrawerMinimized(!0):this.showViewInWrapper(),ao.updateResizerAndSidebarButtons(ao.instance())}willHide(){t.InspectorView.InspectorView.instance().setDrawerMinimized(!1),queueMicrotask((()=>{ao.updateResizerAndSidebarButtons(ao.instance())}))}showViewInWrapper(){this.view.show(this.element)}}const yo=[{viewId:"navigator-network",navigatorView:kt.instance,experiment:void 0},{viewId:"navigator-files",navigatorView:Tt.instance,experiment:void 0},{viewId:"navigator-snippets",navigatorView:Pt.instance,experiment:void 0},{viewId:"navigator-overrides",navigatorView:Lt.instance,experiment:void 0},{viewId:"navigator-contentScripts",navigatorView:Mt.instance,experiment:void 0}];var Eo=Object.freeze({__proto__:null,SourcesPanel:ao,get lastModificationTimeout(){return co},minToolbarWidth:lo,UILocationRevealer:fo,DebuggerLocationRevealer:So,UISourceCodeRevealer:vo,DebuggerPausedDetailsRevealer:Co,RevealingActionDelegate:wo,ActionDelegate:Io,WrapperView:xo});const{EMPTY_BREAKPOINT_CONDITION:ko,NEVER_PAUSE_HERE_CONDITION:To}=f.BreakpointManager,Lo={thisScriptIsOnTheDebuggersIgnore:"This script is on the debugger's ignore list",removeFromIgnoreList:"Remove from ignore list",configure:"Configure",sourceMapFoundButIgnoredForFile:"Source map found, but ignored for file on ignore list.",addBreakpoint:"Add breakpoint",addConditionalBreakpoint:"Add conditional breakpoint…",addLogpoint:"Add logpoint…",neverPauseHere:"Never pause here",removeBreakpoint:"{n, plural, =1 {Remove breakpoint} other {Remove all breakpoints in line}}",editBreakpoint:"Edit breakpoint…",disableBreakpoint:"{n, plural, =1 {Disable breakpoint} other {Disable all breakpoints in line}}",enableBreakpoint:"{n, plural, =1 {Enable breakpoint} other {Enable all breakpoints in line}}",addSourceMap:"Add source map…",addWasmDebugInfo:"Add DWARF debug info…",sourceMapDetected:"Source map detected.",associatedFilesAreAvailable:"Associated files are available via file tree or {PH1}.",associatedFilesShouldBeAdded:"Associated files should be added to the file tree. You can debug these resolved source files as regular JavaScript files.",theDebuggerWillSkipStepping:"The debugger will skip stepping through this script, and will not stop on exceptions.",debugFileNotFound:'Failed to load debug file "{PH1}".',debugInfoNotFound:"Failed to load any debug info for {PH1}."},Mo=e.i18n.registerUIStrings("panels/sources/DebuggerPlugin.ts",Lo),Po=e.i18n.getLocalizedString.bind(void 0,Mo),Fo=new Map;class Do extends re{transformer;editor=void 0;executionLocation=null;controlDown=!1;controlTimeout=void 0;sourceMapInfobar=null;scriptsPanel;breakpointManager;popoverHelper=null;scriptFileForDebuggerModel;breakpoints=[];continueToLocations=null;liveLocationPool;muted;initializedMuted;ignoreListInfobar;refreshBreakpointsTimeout=void 0;activeBreakpointDialog=null;#b=void 0;#f=!1;missingDebugInfoBar=null;#S=!1;ignoreListCallback;constructor(e,i){super(e),this.transformer=i,Fo.set(e,this),this.scriptsPanel=ao.instance(),this.breakpointManager=f.BreakpointManager.BreakpointManager.instance(),this.breakpointManager.addEventListener(f.BreakpointManager.Events.BreakpointAdded,this.breakpointChange,this),this.breakpointManager.addEventListener(f.BreakpointManager.Events.BreakpointRemoved,this.breakpointChange,this),this.uiSourceCode.addEventListener(v.UISourceCode.Events.WorkingCopyChanged,this.workingCopyChanged,this),this.uiSourceCode.addEventListener(v.UISourceCode.Events.WorkingCopyCommitted,this.workingCopyCommitted,this),this.scriptFileForDebuggerModel=new Map,this.ignoreListCallback=this.showIgnoreListInfobarIfNeeded.bind(this),d.IgnoreListManager.IgnoreListManager.instance().addChangeListener(this.ignoreListCallback),t.Context.Context.instance().addFlavorChangeListener(o.DebuggerModel.CallFrame,this.callFrameChanged,this),this.liveLocationPool=new d.LiveLocation.LiveLocationPool,this.updateScriptFiles(),this.muted=this.uiSourceCode.isDirty(),this.initializedMuted=this.muted,this.ignoreListInfobar=null,this.showIgnoreListInfobarIfNeeded();for(const e of this.scriptFileForDebuggerModel.values())e.checkMapping()}editorExtension(){const e=this.shortcutHandlers();return[n.EditorView.updateListener.of((e=>this.onEditorUpdate(e))),n.EditorView.domEventHandlers({keydown:t=>!!this.onKeyDown(t)||(e(t),t.defaultPrevented),keyup:e=>this.onKeyUp(e),mousemove:e=>this.onMouseMove(e),mousedown:e=>this.onMouseDown(e),focusout:e=>this.onBlur(e),wheel:e=>this.onWheel(e)}),n.lineNumbers({domEventHandlers:{mousedown:(e,t,i)=>this.handleGutterClick(e.state.doc.lineAt(t.from),i)}}),Bo,jo,n.Prec.highest(Ko.field),n.Prec.lowest(Xo.field),en,on.field,n.Prec.lowest(dn.field),un,this.uiSourceCode.project().type()===v.Workspace.projectTypes.Debugger?n.EditorView.editorAttributes.of({class:"source-frame-debugger-script"}):[]]}shortcutHandlers(){const e=e=>e.state.doc.lineAt(e.state.selection.main.head);return t.ShortcutRegistry.ShortcutRegistry.instance().getShortcutListener({"debugger.toggle-breakpoint":async()=>!(this.muted||!this.editor)&&(await this.toggleBreakpoint(e(this.editor),!1),!0),"debugger.toggle-breakpoint-enabled":async()=>!(this.muted||!this.editor)&&(await this.toggleBreakpoint(e(this.editor),!0),!0),"debugger.breakpoint-input-window":async()=>{if(this.muted||!this.editor)return!1;const t=e(this.editor);return a.userMetrics.breakpointEditDialogRevealedFrom(4),this.#v(t),!0}})}#v(e){if(this.muted)return;this.activeBreakpointDialog&&this.activeBreakpointDialog.finishEditing(!1,"");const t=this.breakpoints.find((t=>t.position>=e.from&&t.position<=e.to))?.breakpoint||null;this.editBreakpointCondition({line:e,breakpoint:t,location:null,isLogpoint:t?.isLogpoint()})}editorInitialized(e){this.editor=e,async function(e,t,i){const o=d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance(),n=await o.getMappedLines(i);if(!n)return[];const r=[];for(let i=0;i<e.doc.lines;i++){const{lineNumber:o}=t.editorLocationToUILocation(i,0);n.has(o)||r.push(e.doc.line(i+1).from)}return r}(e.state,this.transformer,this.uiSourceCode).then((t=>{t.length&&e.dispatch({effects:p.SourceFrame.addNonBreakableLines.of(t)})}),console.error),this.ignoreListInfobar&&this.attachInfobar(this.ignoreListInfobar),this.missingDebugInfoBar&&this.attachInfobar(this.missingDebugInfoBar),this.sourceMapInfobar&&this.attachInfobar(this.sourceMapInfobar),this.muted||this.refreshBreakpoints(),this.callFrameChanged(),this.popoverHelper?.dispose(),this.popoverHelper=new t.PopoverHelper.PopoverHelper(e,this.getPopoverRequest.bind(this)),this.popoverHelper.setDisableOnClick(!0),this.popoverHelper.setTimeout(250,250),this.popoverHelper.setHasPadding(!0)}static accepts(e){return e.contentType().hasScripts()}showIgnoreListInfobarIfNeeded(){const e=this.uiSourceCode;if(!e.contentType().hasScripts())return;const i=e.project().type();if(!d.IgnoreListManager.IgnoreListManager.instance().isUserOrSourceMapIgnoreListedUISourceCode(e))return void this.hideIgnoreListInfobar();this.ignoreListInfobar&&this.ignoreListInfobar.dispose();const o=new t.Infobar.Infobar(t.Infobar.Type.Warning,Po(Lo.thisScriptIsOnTheDebuggersIgnore),[{text:Po(Lo.removeFromIgnoreList),highlight:!1,delegate:function(){d.IgnoreListManager.IgnoreListManager.instance().unIgnoreListUISourceCode(e),i===v.Workspace.projectTypes.ContentScripts&&d.IgnoreListManager.IgnoreListManager.instance().unIgnoreListContentScripts()},dismiss:!0},{text:Po(Lo.configure),highlight:!1,delegate:t.ViewManager.ViewManager.instance().showView.bind(t.ViewManager.ViewManager.instance(),"blackbox"),dismiss:!1}]);this.ignoreListInfobar=o,o.setCloseCallback((()=>this.removeInfobar(this.ignoreListInfobar))),o.createDetailsRowMessage(Po(Lo.theDebuggerWillSkipStepping));const n=this.scriptFileForDebuggerModel.size?this.scriptFileForDebuggerModel.values().next().value:null;n&&n.hasSourceMapURL()&&o.createDetailsRowMessage(Po(Lo.sourceMapFoundButIgnoredForFile)),this.attachInfobar(this.ignoreListInfobar)}attachInfobar(e){this.editor&&this.editor.dispatch({effects:Uo.of(e)})}removeInfobar(e){this.editor&&e&&this.editor.dispatch({effects:Ro.of(e)})}hideIgnoreListInfobar(){this.ignoreListInfobar&&(this.ignoreListInfobar.dispose(),this.ignoreListInfobar=null)}willHide(){this.popoverHelper?.hidePopover()}editBreakpointLocation({breakpoint:e,uiLocation:t}){const{lineNumber:i}=this.transformer.uiLocationToEditorLocation(t.lineNumber,t.columnNumber),o=this.editor?.state.doc.line(i+1);o&&this.editBreakpointCondition({line:o,breakpoint:e,location:null,isLogpoint:e.isLogpoint()})}populateLineGutterContextMenu(e,t){const i=new v.UISourceCode.UILocation(this.uiSourceCode,t,0);if(this.scriptsPanel.appendUILocationItems(e,i),this.muted||!this.editor)return;const o=this.editor.state.doc.line(t+1),n=this.lineBreakpoints(o),r=d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().supportsConditionalBreakpoints(this.uiSourceCode);if(n.length){const t=Po(Lo.removeBreakpoint,{n:n.length});e.debugSection().appendItem(t,(()=>n.forEach((e=>{e.remove(!1)})))),1===n.length&&r&&e.debugSection().appendItem(Po(Lo.editBreakpoint),(()=>{a.userMetrics.breakpointEditDialogRevealedFrom(2),this.editBreakpointCondition({line:o,breakpoint:n[0],location:null})}));if(n.some((e=>e.enabled()))){const t=Po(Lo.disableBreakpoint,{n:n.length});e.debugSection().appendItem(t,(()=>n.forEach((e=>e.setEnabled(!1)))))}if(n.some((e=>!e.enabled()))){const t=Po(Lo.enableBreakpoint,{n:n.length});e.debugSection().appendItem(t,(()=>n.forEach((e=>e.setEnabled(!0)))))}}else this.editor&&p.SourceFrame.isBreakableLine(this.editor.state,o)&&(e.debugSection().appendItem(Po(Lo.addBreakpoint),this.createNewBreakpoint.bind(this,o,ko,!0,!1)),r&&(e.debugSection().appendItem(Po(Lo.addConditionalBreakpoint),(()=>{a.userMetrics.breakpointEditDialogRevealedFrom(3),this.editBreakpointCondition({line:o,breakpoint:null,location:null,isLogpoint:!1})})),e.debugSection().appendItem(Po(Lo.addLogpoint),(()=>{a.userMetrics.breakpointEditDialogRevealedFrom(3),this.editBreakpointCondition({line:o,breakpoint:null,location:null,isLogpoint:!0})})),e.debugSection().appendItem(Po(Lo.neverPauseHere),this.createNewBreakpoint.bind(this,o,To,!0,!1))))}populateTextAreaContextMenu(e){function t(e,t){t&&e.addSourceMapURL(t)}function o(e,t){t&&e.addDebugInfoURL(t)}if(this.uiSourceCode.project().type()===v.Workspace.projectTypes.Network&&i.Settings.Settings.instance().moduleSetting("jsSourceMapsEnabled").get()&&!d.IgnoreListManager.IgnoreListManager.instance().isUserIgnoreListedURL(this.uiSourceCode.url())&&this.scriptFileForDebuggerModel.size){const i=this.scriptFileForDebuggerModel.values().next().value,n=Po(Lo.addSourceMap);e.debugSection().appendItem(n,function(e){B.createAddSourceMapURLDialog(t.bind(null,e)).show()}.bind(null,i)),i.script?.isWasm()&&!d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().pluginManager?.hasPluginForScript(i.script)&&e.debugSection().appendItem(Po(Lo.addWasmDebugInfo),function(e){B.createAddDWARFSymbolsURLDialog(o.bind(null,e)).show()}.bind(null,i))}}workingCopyChanged(){this.scriptFileForDebuggerModel.size||this.setMuted(this.uiSourceCode.isDirty())}workingCopyCommitted(){this.scriptsPanel.updateLastModificationTime(),this.scriptFileForDebuggerModel.size||this.setMuted(!1)}didMergeToVM(){this.consistentScripts()&&this.setMuted(!1)}didDivergeFromVM(){this.setMuted(!0)}setMuted(e){this.initializedMuted||e!==this.muted&&(this.muted=e,e?this.editor&&this.editor.dispatch({effects:Oo.of(null)}):this.restoreBreakpointsAfterEditing())}consistentScripts(){for(const e of this.scriptFileForDebuggerModel.values())if(e.hasDivergedFromVM()||e.isMergingToVM())return!1;return!0}isVariableIdentifier(e){return"VariableName"===e||"VariableDefinition"===e}isIdentifier(e){return"VariableName"===e||"VariableDefinition"===e||"PropertyName"===e||"PropertyDefinition"===e}getPopoverRequest(e){if(t.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(e))return null;const i=t.Context.Context.instance().flavor(o.Target.Target),r=i?i.model(o.DebuggerModel.DebuggerModel):null,{editor:s}=this;if(!r||!r.isPaused()||!s)return null;const a=t.Context.Context.instance().flavor(o.DebuggerModel.CallFrame);if(!a)return null;let c=s.editor.posAtCoords(e);if(!c)return null;const l=s.editor.coordsAtPos(c);if(!l||e.clientY<l.top||e.clientY>l.bottom||e.clientX<l.left-30||e.clientX>l.right+30)return null;e.clientX<l.left&&c>s.state.doc.lineAt(c).from&&(c-=1);const d=cn(s.state,this.uiSourceCode.mimeType(),c);if(!d)return null;const u=s.state.doc.lineAt(d.from);if(d.to>u.to)return null;const p=s.editor.coordsAtPos(d.from),g=s.editor.coordsAtPos(d.to);if(!p||!g)return null;const m=new AnchorBox(p.left,p.top-2,g.right-p.left,g.bottom-p.top),b=s.state.sliceDoc(d.from,d.to);let f=null;return{box:m,show:async e=>{const i=await h.NamesResolver.resolveExpression(a,b,this.uiSourceCode,u.number-1,d.from-u.from,d.to-u.from),c=await a.evaluate({expression:i||b,objectGroup:"popover",includeCommandLineAPI:!1,silent:!0,returnByValue:!1,generatePreview:!1,throwOnSideEffect:void 0,timeout:void 0,disableBreaks:void 0,replMode:void 0,allowUnsafeEvalBlockedByCSP:void 0});if(!c||"error"in c||!c.object||"object"===c.object.type&&"error"===c.object.subtype)return!1;f=await C.ObjectPopoverHelper.ObjectPopoverHelper.buildObjectPopover(c.object,e);const l=t.Context.Context.instance().flavor(o.DebuggerModel.CallFrame);if(!f||a!==l)return r.runtimeModel().releaseObjectGroup("popover"),f&&f.dispose(),!1;const p=n.Decoration.set(ln.range(d.from,d.to));return s.dispatch({effects:dn.update.of(p)}),!0},hide:()=>{f&&f.dispose(),r.runtimeModel().releaseObjectGroup("popover"),s.dispatch({effects:dn.update.of(n.Decoration.none)})}}}onEditorUpdate(e){if(!e.changes.empty)for(const t of this.breakpoints)t.position=e.changes.mapPos(t.position)}onWheel(e){this.executionLocation&&t.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(e)&&e.preventDefault()}onKeyDown(e){const i=t.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(e);return i||this.setControlDown(!1),e.key===c.KeyboardUtilities.ESCAPE_KEY&&this.popoverHelper&&this.popoverHelper.isPopoverVisible()?(this.popoverHelper.hidePopover(),e.consume(),!0):(i&&this.executionLocation&&this.setControlDown(!0),!1)}onMouseMove(e){this.executionLocation&&this.controlDown&&t.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(e)&&(this.continueToLocations||this.showContinueToLocations())}onMouseDown(e){if(!this.executionLocation||!t.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(e))return;if(!this.continueToLocations||!this.editor)return;e.consume();const i=this.editor.editor.posAtCoords(e);if(null!==i)for(const{from:e,to:t,click:o}of this.continueToLocations)if(e<=i&&t>=i){o();break}}onBlur(e){this.setControlDown(!1)}onKeyUp(e){this.setControlDown(!1)}setControlDown(e){e!==this.controlDown&&(this.controlDown=e,clearTimeout(this.controlTimeout),this.controlTimeout=void 0,e&&this.executionLocation?this.controlTimeout=window.setTimeout((()=>{this.executionLocation&&this.controlDown&&this.showContinueToLocations()}),150):this.clearContinueToLocations())}editBreakpointCondition(e){const{line:t,breakpoint:i,location:o,isLogpoint:r}=e;if(i?.isRemoved)return;this.#f=!1;if(this.#b&&function(e,t){if(e.line.number!==t.line.number)return!1;if(e.line.from!==t.line.from)return!1;if(e.line.text!==t.line.text)return!1;if(e.breakpoint!==t.breakpoint)return!1;if(e.location!==t.location)return!1;return e.isLogpoint===t.isLogpoint}(this.#b,e))return;this.activeBreakpointDialog&&this.activeBreakpointDialog.saveAndFinish();const s=this.editor,c=i?i.condition():"",l=i?.isLogpoint()??Boolean(r),d=document.createElement("div"),u=new n.Compartment,h=new z(t.number-1,c,l,(async e=>{this.activeBreakpointDialog=null,this.#b=void 0,h.detach(),s.dispatch({effects:u.reconfigure([])}),e.committed?(w.BreakpointsView.BreakpointsSidebarController.instance().breakpointEditFinished(i,c!==e.condition),function(e){const{condition:t,isLogpoint:o}=e,n=0!==t.length&&!o,r=i?.isLogpoint(),s=c&&0!==c.length&&!r;o&&!r?a.userMetrics.breakpointWithConditionAdded(0):n&&!s&&a.userMetrics.breakpointWithConditionAdded(1)}(e),i?i.setCondition(e.condition,e.isLogpoint):o?await this.setBreakpoint(o.lineNumber,o.columnNumber,e.condition,!0,e.isLogpoint):await this.createNewBreakpoint(t,e.condition,!0,e.isLogpoint)):w.BreakpointsView.BreakpointsSidebarController.instance().breakpointEditFinished(i,!1)}));s.dispatch({effects:n.StateEffect.appendConfig.of(u.of(n.EditorView.decorations.of(n.Decoration.set([n.Decoration.widget({block:!0,widget:new class extends n.WidgetType{toDOM(){return d}},side:1}).range(t.to)]))))}),h.element.addEventListener("blur",(async e=>{(!e.relatedTarget||e.relatedTarget&&!e.relatedTarget.isSelfOrDescendant(h.element))&&(this.#f=!0,setTimeout((()=>{this.activeBreakpointDialog===h&&(this.#f?(h.saveAndFinish(),this.#f=!1):h.focusEditor())}),200))}),!0),h.markAsExternallyManaged(),h.show(d),h.focusEditor(),this.activeBreakpointDialog=h,this.#b=e}computeExecutionDecorations(e,t,i){const{doc:o}=e;if(t>=o.lines)return n.Decoration.none;const r=o.line(t+1),s=[Go.range(r.from)],a=Math.min(r.to,r.from+i);let c=n.syntaxTree(e).resolveInner(a,1);c.to===c.from-1&&/[(.]/.test(o.sliceString(c.from,c.to))&&(c=c.resolve(c.to,1));const l=Math.min(r.to,c.to);return l>a&&s.push($o.range(a,l)),n.Decoration.set(s)}async updateValueDecorations(){if(!this.editor)return;const e=this.executionLocation?await this.computeValueDecorations():null;this.editor&&(e||this.editor.state.field(on.field).size)&&this.editor.dispatch({effects:on.update.of(e||n.Decoration.none)})}async#C(e,t){const i=e&&await d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().rawLocationToUILocation(e);if(!i||i.uiSourceCode.url()!==t)return null;const o=this.editor?.toOffset(this.transformer.uiLocationToEditorLocation(i.lineNumber,i.columnNumber));return o??null}async computeValueDecorations(){if(!this.editor)return null;if(!i.Settings.Settings.instance().moduleSetting("inlineVariableValues").get())return null;if(!t.Context.Context.instance().flavor(o.RuntimeModel.ExecutionContext))return null;const e=t.Context.Context.instance().flavor(o.DebuggerModel.CallFrame);if(!e)return null;const r=this.uiSourceCode.url(),s=this.#C(e.functionLocation(),r),a=this.#C(e.location(),r),[c,l]=await Promise.all([s,a]);if(!c||!l||!this.editor)return null;if(c>=l||l-c>1e4)return null;const d=rn(this.editor.state,c,l,l);if(0===d.length)return null;const u=await sn(e,(e=>this.#C(e,r)));if(0===u.length)return null;const h=an(u,d);if(!h||!this.editor)return null;const p=[];for(const[e,t]of h){const i=h.get(e-1);let o=i?Array.from(t).filter((e=>i.get(e[0])!==e[1])):Array.from(t);o.length&&(o.length>10&&(o=o.slice(0,10)),p.push(n.Decoration.widget({widget:new tn(o),side:1}).range(this.editor.state.doc.line(e+1).to)))}return n.Decoration.set(p,!0)}async showContinueToLocations(){this.popoverHelper?.hidePopover();if(!t.Context.Context.instance().flavor(o.RuntimeModel.ExecutionContext)||!this.editor)return;const e=t.Context.Context.instance().flavor(o.DebuggerModel.CallFrame);if(!e)return;const i=e.functionLocation()||e.location(),r=e.debuggerModel,{state:s}=this.editor,a=await r.getPossibleBreakpoints(i,null,!0);this.continueToLocations=[];let c=-1;for(const e of a.reverse()){const t=this.transformer.uiLocationToEditorLocation(e.lineNumber,e.columnNumber);if(c===t.lineNumber&&"call"!==e.type||t.lineNumber>=s.doc.lines)continue;const i=s.doc.line(t.lineNumber+1),o=Math.min(i.to,i.from+t.columnNumber);let r=n.syntaxTree(s).resolveInner(o,1);if(r.firstChild||r.from<i.from||r.to>i.to)continue;if("."===r.name){const e=r.resolve(r.to,1);if(e.firstChild||e.from<i.from||e.to>i.to)continue;r=e}const a=r.name,l="this"===a||"return"===a||"new"===a||"break"===a||"continue"===a;if(!l&&!this.isIdentifier(a))continue;this.continueToLocations.push({from:r.from,to:r.to,async:!1,click:()=>e.continueToLocation()}),"call"===e.type&&(c=t.lineNumber);const d=l?"":i.text.slice(r.from-i.from,r.to-i.from);let u=null;if("then"===d&&"MemberExpression"===r.parent?.name?u=r.parent.parent:"setTimeout"!==d&&"setInterval"!==d&&"postMessage"!==d||(u=r.parent),"new"===a){const e=r.parent?.getChild("Expression");e&&"VariableName"===e.name&&"Worker"===s.sliceDoc(e.from,e.to)&&(u=r.parent)}if(u&&("CallExpression"===u.name||"NewExpression"===u.name)&&"call"===e.type){const t=u.getChild("ArgList")?.firstChild?.nextSibling;let i;if("VariableName"===t?.name?i=t:"ArrowFunction"!==t?.name&&"FunctionExpression"!==t?.name||(i=t.firstChild,"async"===i?.name&&(i=i.nextSibling)),i){const t=this.executionLocation&&e.lineNumber===this.executionLocation.lineNumber&&e.columnNumber===this.executionLocation.columnNumber;this.continueToLocations.push({from:i.from,to:i.to,async:!0,click:()=>this.asyncStepIn(e,Boolean(t))})}}}const l=n.Decoration.set(this.continueToLocations.map((e=>(e.async?Yo:Jo).range(e.from,e.to))),!0);this.editor.dispatch({effects:Xo.update.of(l)})}clearContinueToLocations(){this.editor&&this.editor.state.field(Xo.field).size&&this.editor.dispatch({effects:Xo.update.of(n.Decoration.none)})}asyncStepIn(e,t){function i(){e.debuggerModel.scheduleStepIntoAsync()}t?i():e.continueToLocation(i)}fetchBreakpoints(){if(!this.editor)return[];const{editor:e}=this;return this.breakpointManager.breakpointLocationsForUISourceCode(this.uiSourceCode).map((({uiLocation:t,breakpoint:i})=>{const o=this.transformer.uiLocationToEditorLocation(t.lineNumber,t.columnNumber);return{position:e.toOffset(o),breakpoint:i}}))}lineBreakpoints(e){return this.breakpoints.filter((t=>t.position>=e.from&&t.position<=e.to)).map((e=>e.breakpoint))}async computeBreakpointDecoration(e,t){const i=[],o=[],r=new Map,s=new Map,a=[],c=new Set,l=(e,t,i)=>{let o=s.get(e);o||(o=[],s.set(e,o)),o.push({breakpoint:i,column:t})};for(const{position:i,breakpoint:o}of t){const t=e.doc.lineAt(i);let n=r.get(t.from);if(n||(n=[],r.set(t.from,n)),o.enabled()&&n.every((e=>!e.enabled()))){const e=this.transformer.editorLocationToUILocation(t.number-1,0),i=this.transformer.editorLocationToUILocation(t.number-1,Math.min(t.length,2500)),o=new S.TextRange.TextRange(e.lineNumber,e.columnNumber||0,i.lineNumber,i.columnNumber||0);a.push(this.breakpointManager.possibleBreakpoints(this.uiSourceCode,o).then((e=>d(t,e))))}n.push(o),o.enabled()&&(c.add(i),l(t.from,i-t.from,o))}for(const[e,t]of r){const i=t.sort(zo)[0];let n="cm-breakpoint";i.enabled()||(n+=" cm-breakpoint-disabled"),i.bound()||(n+=" cm-breakpoint-unbound"),i.isLogpoint()?n+=" cm-breakpoint-logpoint":i.condition()&&(n+=" cm-breakpoint-conditional"),o.push(new _o(n).range(e))}const d=(e,t)=>{for(const i of t){const t=this.transformer.uiLocationToEditorLocation(i.lineNumber,i.columnNumber);if(t.lineNumber!==e.number-1)continue;const o=Math.min(e.to,e.from+t.columnNumber);c.has(o)||l(e.from,t.columnNumber,null)}};await Promise.all(a);for(const[e,t]of s)if(t.length>1)for(const{column:o,breakpoint:r}of t){const t=new Ho(r,this);i.push(n.Decoration.widget({widget:t,side:-1}).range(e+o))}return{content:n.Decoration.set(i,!0),gutter:n.RangeSet.of(o,!0)}}async restoreBreakpointsAfterEditing(){const{breakpoints:e}=this,t=this.editor;this.breakpoints=[],await Promise.all(e.map((async e=>{const{breakpoint:i,position:o}=e,n=i.condition(),r=i.enabled(),s=i.isLogpoint();await i.remove(!1);const a=t.toLineColumn(o),c=this.transformer.editorLocationToUILocation(a.lineNumber,a.columnNumber);await this.setBreakpoint(c.lineNumber,c.columnNumber,n,r,s)})))}async refreshBreakpoints(){if(this.editor){this.breakpoints=this.fetchBreakpoints();const e=this.breakpoints,t=await this.computeBreakpointDecoration(this.editor.state,e);this.editor&&this.breakpoints===e&&(t.gutter.size||this.editor.state.field(jo,!1)?.gutter.size)&&this.editor.dispatch({effects:Vo.of(t)})}}breakpointChange(e){const{uiLocation:t}=e.data;if(t.uiSourceCode===this.uiSourceCode&&!this.muted){for(const e of this.scriptFileForDebuggerModel.values())if(e.isDivergingFromVM()||e.isMergingToVM())return;window.clearTimeout(this.refreshBreakpointsTimeout),this.refreshBreakpointsTimeout=window.setTimeout((()=>this.refreshBreakpoints()),50)}}onInlineBreakpointMarkerClick(e,t){if(e.consume(!0),t)e.shiftKey?t.setEnabled(!t.enabled()):t.remove(!1);else if(this.editor){const t=this.editor.editor.posAtDOM(e.target),i=this.editor.state.doc.lineAt(t),o=this.transformer.editorLocationToUILocation(i.number-1,t-i.from);this.setBreakpoint(o.lineNumber,o.columnNumber,ko,!0,!1)}}onInlineBreakpointMarkerContextMenu(e,i){e.consume(!0);const o=this.editor,n=o.editor.posAtDOM(e.target),r=o.state.doc.lineAt(n);if(!p.SourceFrame.isBreakableLine(o.state,r)||!d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().supportsConditionalBreakpoints(this.uiSourceCode))return;const s=new t.ContextMenu.ContextMenu(e);if(i)s.debugSection().appendItem(Po(Lo.editBreakpoint),(()=>{a.userMetrics.breakpointEditDialogRevealedFrom(2),this.editBreakpointCondition({line:r,breakpoint:i,location:null})}));else{const e=this.transformer.editorLocationToUILocation(r.number-1,n-r.from);s.debugSection().appendItem(Po(Lo.addConditionalBreakpoint),(()=>{a.userMetrics.breakpointEditDialogRevealedFrom(2),this.editBreakpointCondition({line:r,breakpoint:null,location:e,isLogpoint:!1})})),s.debugSection().appendItem(Po(Lo.addLogpoint),(()=>{a.userMetrics.breakpointEditDialogRevealedFrom(2),this.editBreakpointCondition({line:r,breakpoint:null,location:e,isLogpoint:!0})})),s.debugSection().appendItem(Po(Lo.neverPauseHere),(()=>this.setBreakpoint(e.lineNumber,e.columnNumber,To,!0,!1)))}s.show()}updateScriptFiles(){for(const e of o.TargetManager.TargetManager.instance().models(o.DebuggerModel.DebuggerModel)){d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().scriptFile(this.uiSourceCode,e)&&this.updateScriptFile(e)}}updateScriptFile(e){const t=this.scriptFileForDebuggerModel.get(e),i=d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().scriptFile(this.uiSourceCode,e);this.scriptFileForDebuggerModel.delete(e),t&&(t.removeEventListener("DidMergeToVM",this.didMergeToVM,this),t.removeEventListener("DidDivergeFromVM",this.didDivergeFromVM,this),this.muted&&!this.uiSourceCode.isDirty()&&this.consistentScripts()&&this.setMuted(!1)),i&&(this.scriptFileForDebuggerModel.set(e,i),i.addEventListener("DidMergeToVM",this.didMergeToVM,this),i.addEventListener("DidDivergeFromVM",this.didDivergeFromVM,this),i.checkMapping(),i.hasSourceMapURL()&&this.showSourceMapInfobar(),i.missingSymbolFiles().then((e=>{if(e){const t=Po(Lo.debugInfoNotFound,{PH1:i.uiSourceCode.url()});this.updateMissingDebugInfoInfobar({resources:e,details:t})}else this.updateMissingDebugInfoInfobar(null)})))}updateMissingDebugInfoInfobar(e){if(!this.missingDebugInfoBar){if(null===e)return this.removeInfobar(this.missingDebugInfoBar),void(this.missingDebugInfoBar=null);if(this.missingDebugInfoBar=t.Infobar.Infobar.create(t.Infobar.Type.Error,e.details,[]),this.missingDebugInfoBar){for(const t of e.resources){const e=this.missingDebugInfoBar?.createDetailsRowMessage(Po(Lo.debugFileNotFound,{PH1:t}));e&&e.classList.add("infobar-selectable")}this.missingDebugInfoBar.setCloseCallback((()=>{this.removeInfobar(this.missingDebugInfoBar),this.missingDebugInfoBar=null})),this.attachInfobar(this.missingDebugInfoBar)}}}showSourceMapInfobar(){this.sourceMapInfobar||i.Settings.Settings.instance().moduleSetting("jsSourceMapsEnabled").get()&&(this.sourceMapInfobar=t.Infobar.Infobar.create(t.Infobar.Type.Info,Po(Lo.sourceMapDetected),[],i.Settings.Settings.instance().createSetting("sourceMapInfobarDisabled",!1)),this.sourceMapInfobar&&(this.sourceMapInfobar.createDetailsRowMessage(Po(Lo.associatedFilesShouldBeAdded)),this.sourceMapInfobar.createDetailsRowMessage(Po(Lo.associatedFilesAreAvailable,{PH1:String(t.ShortcutRegistry.ShortcutRegistry.instance().shortcutTitleForAction("quickOpen.show"))})),this.sourceMapInfobar.setCloseCallback((()=>{this.removeInfobar(this.sourceMapInfobar),this.sourceMapInfobar=null})),this.attachInfobar(this.sourceMapInfobar)))}handleGutterClick(e,t){return!this.muted&&0===t.button&&!t.altKey&&(t.metaKey||t.ctrlKey?!t.shiftKey&&(a.userMetrics.breakpointEditDialogRevealedFrom(6),this.#v(e),!0):(this.toggleBreakpoint(e,t.shiftKey),!0))}async toggleBreakpoint(e,t){if(this.muted)return;this.activeBreakpointDialog&&this.activeBreakpointDialog.finishEditing(!1,"");const i=this.lineBreakpoints(e);if(!i.length)return void await this.createNewBreakpoint(e,ko,!0,!1);const o=i.some((e=>!e.enabled()));for(const e of i)t?e.setEnabled(o):e.remove(!1)}async createNewBreakpoint(e,t,i,o){if(!this.editor||!p.SourceFrame.isBreakableLine(this.editor.state,e))return;a.userMetrics.actionTaken(a.UserMetrics.Action.ScriptsBreakpointSet),this.#w();const n=this.transformer.editorLocationToUILocation(e.number-1);await this.setBreakpoint(n.lineNumber,n.columnNumber,t,i,o)}async setBreakpoint(e,t,o,n,r){i.Settings.Settings.instance().moduleSetting("breakpointsActive").set(!0);const s=await this.breakpointManager.setBreakpoint(this.uiSourceCode,e,t,o,n,r,"USER_ACTION");return this.breakpointWasSetForTest(e,t,o,n),s}breakpointWasSetForTest(e,t,i,o){}async callFrameChanged(){this.liveLocationPool.disposeAll();const e=t.Context.Context.instance().flavor(o.DebuggerModel.CallFrame);e?await d.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().createCallFrameLiveLocation(e.location(),(async t=>{const i=await t.uiLocation();i&&i.uiSourceCode===this.uiSourceCode?(this.setExecutionLocation(i),this.updateMissingDebugInfoInfobar(e.missingDebugInfoDetails),this.#w()):this.setExecutionLocation(null)}),this.liveLocationPool):this.setExecutionLocation(null)}setExecutionLocation(e){if(this.executionLocation!==e&&this.editor)if(this.executionLocation=e,e){const t=this.transformer.uiLocationToEditorLocation(e.lineNumber,e.columnNumber),i=this.computeExecutionDecorations(this.editor.state,t.lineNumber,t.columnNumber);this.editor.dispatch({effects:Ko.update.of(i)}),this.updateValueDecorations(),this.controlDown&&this.showContinueToLocations()}else this.editor.dispatch({effects:[Ko.update.of(n.Decoration.none),Xo.update.of(n.Decoration.none),on.update.of(n.Decoration.none)]})}dispose(){this.hideIgnoreListInfobar(),this.sourceMapInfobar&&this.sourceMapInfobar.dispose();for(const e of this.scriptFileForDebuggerModel.values())e.removeEventListener("DidMergeToVM",this.didMergeToVM,this),e.removeEventListener("DidDivergeFromVM",this.didDivergeFromVM,this);this.scriptFileForDebuggerModel.clear(),this.popoverHelper?.hidePopover(),this.popoverHelper?.dispose(),this.setExecutionLocation(null),this.breakpointManager.removeEventListener(f.BreakpointManager.Events.BreakpointAdded,this.breakpointChange,this),this.breakpointManager.removeEventListener(f.BreakpointManager.Events.BreakpointRemoved,this.breakpointChange,this),this.uiSourceCode.removeEventListener(v.UISourceCode.Events.WorkingCopyChanged,this.workingCopyChanged,this),this.uiSourceCode.removeEventListener(v.UISourceCode.Events.WorkingCopyCommitted,this.workingCopyCommitted,this),d.IgnoreListManager.IgnoreListManager.instance().removeChangeListener(this.ignoreListCallback),Fo.delete(this.uiSourceCode),super.dispose(),window.clearTimeout(this.refreshBreakpointsTimeout),this.editor=void 0,t.Context.Context.instance().removeFlavorChangeListener(o.DebuggerModel.CallFrame,this.callFrameChanged,this),this.liveLocationPool.disposeAll()}#w(){if(this.#S)return;this.#S=!0;const e=i.ResourceType.ResourceType.mimeFromURL(this.uiSourceCode.url()),t=i.ResourceType.ResourceType.mediaTypeForMetrics(e??"",this.uiSourceCode.contentType().isFromSourceMap(),S.TextUtils.isMinified(this.uiSourceCode.content()));a.userMetrics.sourcesPanelFileDebugged(t)}}let No;class Ao{static instance({forceNew:e}={forceNew:!1}){return No&&!e||(No=new Ao),No}async reveal(e,t){if(!(e instanceof f.BreakpointManager.BreakpointLocation))throw new Error("Internal error: not a breakpoint location");const{uiLocation:i}=e;ao.instance().showUILocation(i,t);const o=Fo.get(i.uiSourceCode);o?o.editBreakpointLocation(e):w.BreakpointsView.BreakpointsSidebarController.instance().breakpointEditFinished(e.breakpoint,!1)}}const Uo=n.StateEffect.define(),Ro=n.StateEffect.define(),Bo=n.StateField.define({create:()=>[],update(e,t){for(const i of t.effects)i.is(Uo)?e=e.concat(i.value):i.is(Ro)&&(e=e.filter((e=>e!==i.value)));return e},provide:e=>n.showPanel.computeN([e],(t=>t.field(e).map((e=>()=>({dom:e.element})))))});const Vo=n.StateEffect.define(),Oo=n.StateEffect.define();function Wo(e,t){const i=[];return e.between(0,t.length,((e,t,o)=>{let n=o.elementClass;/cm-breakpoint-disabled/.test(n)||(n+=" cm-breakpoint-disabled"),i.push(new _o(n).range(e))})),n.RangeSet.of(i,!1)}const jo=n.StateField.define({create:()=>({content:n.RangeSet.empty,gutter:n.RangeSet.empty}),update(e,t){t.changes.empty||(e={content:e.content.map(t.changes),gutter:e.gutter.map(t.changes)});for(const i of t.effects)i.is(Vo)?e=i.value:i.is(Oo)&&(e={content:n.RangeSet.empty,gutter:Wo(e.gutter,t.state.doc)});return e},provide:e=>[n.EditorView.decorations.from(e,(e=>e.content)),n.lineNumberMarkers.from(e,(e=>e.gutter))]});class Ho extends n.WidgetType{breakpoint;parent;class;constructor(e,t){super(),this.breakpoint=e,this.parent=t,this.class="cm-inlineBreakpoint",e?.isLogpoint()?this.class+=" cm-inlineBreakpoint-logpoint":e?.condition()&&(this.class+=" cm-inlineBreakpoint-conditional"),e?.enabled()||(this.class+=" cm-inlineBreakpoint-disabled")}eq(e){return e.class===this.class&&e.breakpoint===this.breakpoint}toDOM(){const e=document.createElement("span");return e.className=this.class,e.addEventListener("click",(e=>{this.parent.onInlineBreakpointMarkerClick(e,this.breakpoint),e.consume()})),e.addEventListener("contextmenu",(e=>{this.parent.onInlineBreakpointMarkerContextMenu(e,this.breakpoint),e.consume()})),e}ignoreEvent(){return!0}}class _o extends n.GutterMarker{elementClass;constructor(e){super(),this.elementClass=e}eq(e){return e.elementClass===this.elementClass}}function zo(e,t){return e.enabled()!==t.enabled()?e.enabled()?-1:1:e.bound()!==t.bound()?e.bound()?-1:1:Boolean(e.condition())!==Boolean(t.condition())?Boolean(e.condition())?-1:1:0}function qo(){const e=n.StateEffect.define(),t=n.StateField.define({create:()=>n.Decoration.none,update:(t,i)=>i.effects.reduce(((t,i)=>i.is(e)?i.value:t),t.map(i.changes)),provide:e=>n.EditorView.decorations.from(e)});return{update:e,field:t}}const Go=n.Decoration.line({attributes:{class:"cm-executionLine"}}),$o=n.Decoration.mark({attributes:{class:"cm-executionToken"}}),Ko=qo(),Jo=n.Decoration.mark({class:"cm-continueToLocation"}),Yo=n.Decoration.mark({class:"cm-continueToLocation cm-continueToLocation-async"}),Xo=qo(),Qo={},Zo={class:"cm-hasContinueMarkers"},en=n.EditorView.contentAttributes.compute([Xo.field],(e=>e.field(Xo.field).size?Zo:Qo));class tn extends n.WidgetType{pairs;constructor(e){super(),this.pairs=e}eq(e){return this.pairs.length===e.pairs.length&&this.pairs.every(((t,i)=>t[0]===e.pairs[i][0]&&t[1]===e.pairs[i][1]))}toDOM(){const e=new C.RemoteObjectPreviewFormatter.RemoteObjectPreviewFormatter,i=document.createElement("div");i.classList.add("cm-variableValues");let o=!0;for(const[n,r]of this.pairs){o?o=!1:t.UIUtils.createTextChild(i,", ");const s=i.createChild("span");t.UIUtils.createTextChild(s,n+" = ");const a=r.preview?r.preview.properties.length:0,c=r.preview&&r.preview.entries?r.preview.entries.length:0;if(r.preview&&a+c<10)e.appendObjectPreview(s,r.preview,!1);else{const e=C.ObjectPropertiesSection.ObjectPropertiesSection.createPropertyValue(r,!1,!1);s.appendChild(e.element)}}return i}}const on=qo();class nn{blockList=new Set;variables=[]}function rn(e,t,i,o){const r=e.doc.lineAt(t);t=Math.min(r.to,t),i=e.doc.lineAt(i).from;const s=n.ensureSyntaxTree(e,i,100);if(!s)return[];function a(e){return("Block"===(t=e.name)||"ForSpec"===t)&&(e.to<o||o<e.from);var t}const c=[];let l=r;const d=[];let u=null;function h(){return d.length?d[d.length-1].variables:c}return s.iterate({from:t,to:i,enter:i=>{if(i.from<t)return;if("let"===(o=i.name)||"const"===o)return void(u=i.node.nextSibling);var o;if(a(i))return void d.push(new nn);const n=function(e){return"VariableName"===e||"VariableDefinition"===e}(i.name)&&e.sliceDoc(i.from,i.to);n&&(u&&function(e){return"VariableDefinition"===e}(i.name)&&d.length>0?d[d.length-1].blockList.add(n):(i.from>l.to&&(l=e.doc.lineAt(i.from)),h().push({line:l.number-1,from:i.from,id:n})))},leave:e=>{if(u===e.node)u=null;else if(a(e)){const e=d.pop(),t=h();for(const i of e?.variables??[])e?.blockList.has(i.id)||t.push(i)}}}),c}async function sn(e,t){const i=[];for(const o of e.scopeChain()){const e=await t(o.startLocation());if(!e)break;const n=await t(o.endLocation());if(!n)break;const{properties:r}=await h.NamesResolver.resolveScopeInObject(o).getAllProperties(!1,!1);if(!r||r.length>500)break;const s=new Map(r.map((e=>[e.name,e.value])));if(i.push({scopeStart:e,scopeEnd:n,variableMap:s}),"local"===o.type())break}return i}function an(e,t){const i=new Map;for(const{line:n,from:r,id:s}of t){const t=o(s,r,e);if(!t)continue;let a=i.get(n);a||(a=new Map,i.set(n,a)),a.set(s,t)}return i;function o(e,t,i){for(const o of i){if(t<o.scopeStart||t>=o.scopeEnd)continue;const i=o.variableMap.get(e);if(i)return i}return null}}function cn(e,t,i){const{main:o}=e.selection;if(!o.empty)return i<o.from||o.to<i?null:{from:o.from,to:o.to};const r=n.ensureSyntaxTree(e,i,5e3);if(!r)return null;const s=r.resolveInner(i,1);if(s.firstChild)return null;switch(t){case"application/wasm":{if("Identifier"!==s.name)return null;const t=["block","loop","if","else","end","br","br_if","br_table"];for(let i=s.parent;i;i=i.parent)if("App"===i.name){const o=i.firstChild,n="Keyword"===o?.name&&e.sliceDoc(o.from,o.to);if(n&&t.includes(n))return null}return{from:s.from,to:s.to}}case"text/html":case"text/javascript":case"text/jsx":case"text/typescript":case"text/typescript-jsx":{let e=s;for(;e&&"this"!==e.name&&"VariableDefinition"!==e.name&&"VariableName"!==e.name&&"MemberExpression"!==e.name&&("PropertyName"!==e.name||"PatternProperty"!==e.parent?.name||":"===e.nextSibling?.name)&&("PropertyDefinition"!==e.name||"Property"!==e.parent?.name||":"===e.nextSibling?.name);)e=e.parent;return e?{from:e.from,to:e.to}:null}default:return s.to-s.from>50||/[^\w_\-$]/.test(e.sliceDoc(s.from,s.to))?null:{from:s.from,to:s.to}}}const ln=n.Decoration.mark({class:"cm-evaluatedExpression"}),dn=qo(),un=n.EditorView.baseTheme({".cm-gutters .cm-gutter.cm-lineNumbers .cm-gutterElement":{"&:hover, &.cm-breakpoint":{borderStyle:"solid",borderWidth:"1px 4px 1px 1px",marginRight:"-4px",paddingLeft:"8px",lineHeight:"calc(1.2em - 2px)",position:"relative"},"&:hover":{WebkitBorderImage:hn("#ebeced","#ebeced")},"&.cm-breakpoint":{color:"#fff",WebkitBorderImage:hn("#4285f4","#1a73e8")},"&.cm-breakpoint-conditional":{WebkitBorderImage:hn("#f29900","#e37400"),"&::before":{content:'"?"',position:"absolute",top:0,left:"1px"}},"&.cm-breakpoint-logpoint":{WebkitBorderImage:hn("#f439a0","#d01884"),"&::before":{content:'"‥"',position:"absolute",top:"-3px",left:"1px"}}},"&dark .cm-gutters .cm-gutter.cm-lineNumbers .cm-gutterElement":{"&:hover":{WebkitBorderImage:hn("#3c4043","#3c4043")},"&.cm-breakpoint":{WebkitBorderImage:hn("#5186EC","#1a73e8")},"&.cm-breakpoint-conditional":{WebkitBorderImage:hn("#e9a33a","#e37400")},"&.cm-breakpoint-logpoint":{WebkitBorderImage:hn("#E54D9B","#d01884")}},":host-context(.breakpoints-deactivated) & .cm-gutters .cm-gutter.cm-lineNumbers .cm-gutterElement.cm-breakpoint, .cm-gutters .cm-gutter.cm-lineNumbers .cm-gutterElement.cm-breakpoint-disabled":{color:"#1a73e8",WebkitBorderImage:hn("#d9e7fd","#1a73e8"),"&.cm-breakpoint-conditional":{color:"#e37400",WebkitBorderImage:hn("#fcebcc","#e37400")},"&.cm-breakpoint-logpoint":{color:"#d01884",WebkitBorderImage:hn("#fdd7ec","#f439a0")}},":host-context(.breakpoints-deactivated) &dark .cm-gutters .cm-gutter.cm-lineNumbers .cm-gutterElement.cm-breakpoint, &dark .cm-gutters .cm-gutter.cm-lineNumbers .cm-gutterElement.cm-breakpoint-disabled":{WebkitBorderImage:hn("#2a384e","#1a73e8"),"&.cm-breakpoint-conditional":{WebkitBorderImage:hn("#4d3c1d","#e37400")},"&.cm-breakpoint-logpoint":{WebkitBorderImage:hn("#4e283d","#f439a0")}},".cm-inlineBreakpoint":{cursor:"pointer",position:"relative",top:"1px",content:pn("#4285F4","#1A73E8"),height:"10px","&.cm-inlineBreakpoint-conditional":{content:gn("#F29900","#E37400")},"&.cm-inlineBreakpoint-logpoint":{content:mn("#F439A0","#D01884")}},"&dark .cm-inlineBreakpoint":{content:pn("#5186EC","#1A73E8"),"&.cm-inlineBreakpoint-conditional":{content:gn("#e9a33a","#E37400")},"&.cm-inlineBreakpoint-logpoint":{content:mn("#E54D9B","#D01884")}},":host-context(.breakpoints-deactivated) & .cm-inlineBreakpoint, .cm-inlineBreakpoint-disabled":{content:pn("#4285F4","#1A73E8","0.2"),"&.cm-inlineBreakpoint-conditional":{content:gn("#F9AB00","#E37400","0.2")},"&.cm-inlineBreakpoint-logpoint":{content:mn("#F439A0","#D01884","0.2")}},".cm-executionLine":{backgroundColor:"var(--color-execution-line-background)",outline:"1px solid var(--color-execution-line-outline)",".cm-hasContinueMarkers &":{backgroundColor:"transparent"},"&.cm-highlightedLine":{animation:"cm-fading-highlight-execution 2s 0s"}},".cm-executionToken":{backgroundColor:"var(--color-execution-token-background)"},"@keyframes cm-fading-highlight-execution":{from:{backgroundColor:"var(--color-highlighted-line)"},to:{backgroundColor:"var(--color-execution-line-background)"}},".cm-continueToLocation":{cursor:"pointer",backgroundColor:"var(--color-continue-to-location)","&:hover":{backgroundColor:"var(--color-continue-to-location-hover)",border:"1px solid var(--color-continue-to-location-hover-border)",margin:"0 -1px"},"&.cm-continueToLocation-async":{backgroundColor:"var(--color-continue-to-location-async)","&:hover":{backgroundColor:"var(--color-continue-to-location-async-hover)",border:"1px solid var(--color-continue-to-location-async-hover-border)",margin:"0 -1px"}}},".cm-evaluatedExpression":{backgroundColor:"var(--color-evaluated-expression)",border:"1px solid var(--color-evaluated-expression-border)",margin:"0 -1px"},".cm-variableValues":{display:"inline",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"1000px",opacity:"80%",backgroundColor:"var(--color-variable-values)",marginLeft:"10px",padding:"0 5px",userSelect:"text",".cm-executionLine &":{backgroundColor:"transparent",opacity:"50%"}}});function hn(e,t){return`url('data:image/svg+xml,<svg height="11" width="26" xmlns="http://www.w3.org/2000/svg"><path d="M22.8.5l2.7 5-2.7 5H.5V.5z" fill="${encodeURIComponent(e)}" stroke="${encodeURIComponent(t)}"/></svg>') 1 3 1 1`}function pn(e,t,i="1"){return`url('data:image/svg+xml,<svg width="11" height="12" viewBox="0 0 11 12" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0.5 0.5H5.80139C6.29382 0.5 6.7549 0.741701 7.03503 1.14669L10.392 6L7.03503 10.8533C6.7549 11.2583 6.29382 11.5 5.80139 11.5H0.5V0.5Z" fill="${encodeURIComponent(e)}" stroke="${encodeURIComponent(t)}" fill-opacity="${encodeURIComponent(i)}"/></svg>')`}function gn(e,t,i="1"){return`url('data:image/svg+xml,<svg width="11" height="12" viewBox="0 0 11 12" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0.5 0.5H5.80139C6.29382 0.5 6.75489 0.741701 7.03503 1.14669L10.392 6L7.03503 10.8533C6.75489 11.2583 6.29382 11.5 5.80138 11.5H0.5V0.5Z" fill="${encodeURIComponent(e)}" fill-opacity="${encodeURIComponent(i)}" stroke="${encodeURIComponent(t)}"/><path d="M3.51074 7.75635H4.68408V9H3.51074V7.75635ZM4.68408 7.23779H3.51074V6.56104C3.51074 6.271 3.55615 6.02344 3.64697 5.81836C3.73779 5.61328 3.90039 5.39648 4.13477 5.16797L4.53027 4.77686C4.71484 4.59814 4.83936 4.4502 4.90381 4.33301C4.97119 4.21582 5.00488 4.09424 5.00488 3.96826C5.00488 3.77197 4.9375 3.62402 4.80273 3.52441C4.66797 3.4248 4.46582 3.375 4.19629 3.375C3.9502 3.375 3.69238 3.42773 3.42285 3.5332C3.15625 3.63574 2.88232 3.78955 2.60107 3.99463V2.81689C2.88818 2.65283 3.17822 2.52979 3.47119 2.44775C3.76709 2.36279 4.06299 2.32031 4.35889 2.32031C4.95068 2.32031 5.41504 2.45801 5.75195 2.7334C6.08887 3.00879 6.25732 3.38818 6.25732 3.87158C6.25732 4.09424 6.20752 4.30225 6.10791 4.49561C6.0083 4.68604 5.8208 4.91602 5.54541 5.18555L5.15869 5.56348C4.95947 5.75684 4.83203 5.91504 4.77637 6.03809C4.7207 6.16113 4.69287 6.31201 4.69287 6.49072C4.69287 6.51709 4.69141 6.54785 4.68848 6.58301C4.68848 6.61816 4.68701 6.65625 4.68408 6.69727V7.23779Z" fill="white"/></svg>')`}function mn(e,t,i="1"){return`url('data:image/svg+xml,<svg width="11" height="12" viewBox="0 0 11 12" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0.5 0.5H5.80139C6.29382 0.5 6.7549 0.741701 7.03503 1.14669L10.392 6L7.03503 10.8533C6.7549 11.2583 6.29382 11.5 5.80139 11.5H0.5V0.5Z" fill="${encodeURIComponent(e)}" stroke="${encodeURIComponent(t)}" fill-opacity="${encodeURIComponent(i)}"/><circle cx="3" cy="6" r="1" fill="white"/><circle cx="7" cy="6" r="1" fill="white"/></svg>')`}var bn=Object.freeze({__proto__:null,DebuggerPlugin:Do,BreakpointLocationRevealer:Ao,getVariableNamesByLine:rn,computeScopeMappings:sn,getVariableValuesByLine:an,computePopoverHighlightRange:cn});class fn{query;queryUpperCase;score;sequence;dataUpperCase;fileNameIndex;constructor(e){this.query=e,this.queryUpperCase=e.toUpperCase(),this.score=new Int32Array(2e3),this.sequence=new Int32Array(2e3),this.dataUpperCase="",this.fileNameIndex=0}calculateScore(e,t){if(!e||!this.query)return 0;const i=this.query.length,o=e.length;(!this.score||this.score.length<i*o)&&(this.score=new Int32Array(i*o*2),this.sequence=new Int32Array(i*o*2));const n=this.score,r=this.sequence;this.dataUpperCase=e.toUpperCase(),this.fileNameIndex=e.lastIndexOf("/");for(let t=0;t<i;++t)for(let i=0;i<o;++i){const s=0===i?0:n[t*o+i-1],a=0===t||0===i?0:n[(t-1)*o+i-1],c=0===t||0===i?0:r[(t-1)*o+i-1],l=this.match(this.query,e,t,i,c);l&&a+l>=s?(r[t*o+i]=c+1,n[t*o+i]=a+l):(r[t*o+i]=0,n[t*o+i]=s)}t&&this.restoreMatchIndexes(r,i,o,t);return 256*n[i*o-1]+(256-e.length)}testWordStart(e,t){if(0===t)return!0;const i=e.charAt(t-1);return"_"===i||"-"===i||"/"===i||"."===i||" "===i||e[t-1]!==this.dataUpperCase[t-1]&&e[t]===this.dataUpperCase[t]}restoreMatchIndexes(e,t,i,o){let n=t-1,r=i-1;for(;n>=0&&r>=0;)if(0===e[n*i+r])--r;else o.push(r),--n,--r;o.reverse()}singleCharScore(e,t,i,o){const n=this.testWordStart(t,o),r=o>this.fileNameIndex;let s=10;return(0===o||"/"===t[o-1])&&(s+=4),n&&(s+=2),e[i]===t[o]&&e[i]===this.queryUpperCase[i]&&(s+=6),r&&(s+=4),o===this.fileNameIndex+1&&0===i&&(s+=5),r&&n&&(s+=3),s}sequenceCharScore(e,t,i,o,n){let r=10;return o>this.fileNameIndex&&(r+=4),(0===o||"/"===t[o-1])&&(r+=5),r+=4*n,r}match(e,t,i,o,n){return this.queryUpperCase[i]!==this.dataUpperCase[o]?0:n?this.sequenceCharScore(e,t,i,o-n,n):this.singleCharScore(e,t,i,o)}}var Sn=Object.freeze({__proto__:null,FilePathScoreFunction:fn});const vn={noFilesFound:"No files found",sIgnoreListed:"{PH1} (ignore listed)"},Cn=e.i18n.registerUIStrings("panels/sources/FilteredUISourceCodeListProvider.ts",vn),wn=e.i18n.getLocalizedString.bind(void 0,Cn);class In extends k.FilteredListWidget.Provider{queryLineNumberAndColumnNumber;defaultScores;scorer;uiSourceCodes;uiSourceCodeIds;query;constructor(){super(),this.queryLineNumberAndColumnNumber="",this.defaultScores=null,this.scorer=new fn(""),this.uiSourceCodes=[],this.uiSourceCodeIds=new Set}projectRemoved(e){const t=e.data;this.populate(t),this.refresh()}populate(e){this.uiSourceCodes=[],this.uiSourceCodeIds.clear();for(const t of v.Workspace.WorkspaceImpl.instance().projects())if(t!==e&&this.filterProject(t))for(const e of t.uiSourceCodes())this.filterUISourceCode(e)&&(this.uiSourceCodes.push(e),this.uiSourceCodeIds.add(e.canononicalScriptId()))}filterUISourceCode(e){if(this.uiSourceCodeIds.has(e.canononicalScriptId()))return!1;if(I.Runtime.experiments.isEnabled(I.Runtime.ExperimentName.JUST_MY_CODE)&&d.IgnoreListManager.IgnoreListManager.instance().isUserOrSourceMapIgnoreListedUISourceCode(e))return!1;const t=u.Persistence.PersistenceImpl.instance().binding(e);return!t||t.fileSystem===e}uiSourceCodeSelected(e,t,i){}filterProject(e){return!0}itemCount(){return this.uiSourceCodes.length}itemContentTypeAt(e){return this.uiSourceCodes[e].contentType()}itemKeyAt(e){return this.uiSourceCodes[e].url()}setDefaultScores(e){this.defaultScores=e}itemScoreAt(e,t){const i=this.uiSourceCodes[e],o=this.defaultScores&&this.defaultScores.get(i)||0;if(!t||t.length<2)return o;this.query!==t&&(this.query=t,this.scorer=new fn(t));let n=10;i.project().type()!==v.Workspace.projectTypes.FileSystem||u.Persistence.PersistenceImpl.instance().binding(i)||(n=5);let r=0;i.contentType().isFromSourceMap()&&!i.isKnownThirdParty()&&(r=100),i.contentType().isScript()&&(d.IgnoreListManager.IgnoreListManager.instance().isUserOrSourceMapIgnoreListedUISourceCode(i)||(r+=50));const s=i.fullDisplayName();return o+n*(r+this.scorer.calculateScore(s,null))}renderItem(e,i,o,n){i=this.rewriteQuery(i);const r=this.uiSourceCodes[e],s=r.fullDisplayName(),a=[];new fn(i).calculateScore(s,a);const c=s.lastIndexOf("/");let l=s;d.IgnoreListManager.IgnoreListManager.instance().isUserOrSourceMapIgnoreListedUISourceCode(r)&&(o.parentElement?.classList.add("is-ignore-listed"),l=wn(vn.sIgnoreListed,{PH1:l})),o.textContent=r.displayName()+(this.queryLineNumberAndColumnNumber||""),this.renderSubtitleElement(n,s.substring(0,c+1)),t.Tooltip.Tooltip.install(n,l);const u=[];for(let e=0;e<a.length;++e)u.push({offset:a[e],length:1});if(a[0]>c){for(let e=0;e<u.length;++e)u[e].offset-=c+1;t.UIUtils.highlightRangesWithStyleClass(o,u,"highlight")}else t.UIUtils.highlightRangesWithStyleClass(n,u,"highlight")}renderSubtitleElement(e,i){e.removeChildren();let o=i.lastIndexOf("/");i.length>43&&(o=i.length-43);e.createChild("div","first-part").textContent=i.substring(0,o);e.createChild("div","second-part").textContent=i.substring(o),t.Tooltip.Tooltip.install(e,i)}selectItem(e,t){const i=t.trim().match(/^([^:]*)(:\d+)?(:\d+)?$/);if(!i)return;let o,n;i[2]&&(o=parseInt(i[2].substr(1),10)-1),i[3]&&(n=parseInt(i[3].substr(1),10)-1);const r=null!==e?this.uiSourceCodes[e]:null;this.uiSourceCodeSelected(r,o,n)}rewriteQuery(e){if(!(e=e?e.trim():"")||":"===e)return"";const t=e.match(/^([^:]+)((?::[^:]*){0,2})$/);return this.queryLineNumberAndColumnNumber=t?t[2]:"",t?t[1]:e}uiSourceCodeAdded(e){const t=e.data;this.filterUISourceCode(t)&&this.filterProject(t.project())&&(this.uiSourceCodes.push(t),this.uiSourceCodeIds.add(t.canononicalScriptId()),this.refresh())}notFoundText(){return wn(vn.noFilesFound)}attach(){v.Workspace.WorkspaceImpl.instance().addEventListener(v.Workspace.Events.UISourceCodeAdded,this.uiSourceCodeAdded,this),v.Workspace.WorkspaceImpl.instance().addEventListener(v.Workspace.Events.ProjectRemoved,this.projectRemoved,this),this.populate()}detach(){v.Workspace.WorkspaceImpl.instance().removeEventListener(v.Workspace.Events.UISourceCodeAdded,this.uiSourceCodeAdded,this),v.Workspace.WorkspaceImpl.instance().removeEventListener(v.Workspace.Events.ProjectRemoved,this.projectRemoved,this),this.queryLineNumberAndColumnNumber="",this.defaultScores=null}}var xn=Object.freeze({__proto__:null,FilteredUISourceCodeListProvider:In});const yn={noFileSelected:"No file selected.",noResultsFound:"No results found",typeANumberToGoToThatLine:"Type a number to go to that line.",currentPositionXsTypeAnOffset:"Current position: 0x{PH1}. Type an offset between 0x{PH2} and 0x{PH3} to navigate to.",currentLineSTypeALineNumber:"Current line: {PH1}. Type a line number between 1 and {PH2} to navigate to.",goToOffsetXs:"Go to offset 0x{PH1}.",goToLineSAndColumnS:"Go to line {PH1} and column {PH2}.",goToLineS:"Go to line {PH1}."},En=e.i18n.registerUIStrings("panels/sources/GoToLineQuickOpen.ts",yn),kn=e.i18n.getLocalizedString.bind(void 0,En);class Tn extends k.FilteredListWidget.Provider{#I=[];selectItem(e,t){const i=this.currentSourceFrame();if(!i)return;const o=this.parsePosition(t);o&&i.revealPosition({lineNumber:o.line-1,columnNumber:o.column-1})}itemCount(){return this.#I.length}renderItem(e,i,o,n){t.UIUtils.createTextChild(o,this.#I[e])}rewriteQuery(e){return""}queryChanged(e){this.#I=[];const t=this.parsePosition(e),i=this.currentSourceFrame();if(t)i&&i.wasmDisassembly?this.#I.push(kn(yn.goToOffsetXs,{PH1:(t.column-1).toString(16)})):t.column&&t.column>1?this.#I.push(kn(yn.goToLineSAndColumnS,{PH1:t.line,PH2:t.column})):i&&t.line>i.textEditor.state.doc.lines||this.#I.push(kn(yn.goToLineS,{PH1:t.line}));else{if(!i)return void this.#I.push(kn(yn.typeANumberToGoToThatLine));const e=i.textEditor.state,t=i.wasmDisassembly,o=i.editorLocationToUILocation(e.doc.lineAt(e.selection.main.head).number-1).lineNumber;if(t){const e=t.lineNumberToBytecodeOffset(t.lineNumbers-1),i=e.toString(16).length,n=t.lineNumberToBytecodeOffset(o);return void this.#I.push(kn(yn.currentPositionXsTypeAnOffset,{PH1:n.toString(16).padStart(i,"0"),PH2:"0".padStart(i,"0"),PH3:e.toString(16)}))}const n=i.editorLocationToUILocation(e.doc.lines-1).lineNumber+1;this.#I.push(kn(yn.currentLineSTypeALineNumber,{PH1:o+1,PH2:n}))}}notFoundText(e){return this.currentSourceFrame()?kn(yn.noResultsFound):kn(yn.noFileSelected)}parsePosition(e){const t=this.currentSourceFrame();if(t&&t.wasmDisassembly){const t=e.match(/0x([0-9a-fA-F]+)/);if(!t||!t[0]||t[0].length!==e.length)return null;return{line:0,column:parseInt(t[0],16)+1}}const i=e.match(/([0-9]+)(\:[0-9]*)?/);if(!i||!i[0]||i[0].length!==e.length)return null;const o=parseInt(i[1],10);let n=0;return i[2]&&(n=parseInt(i[2].substring(1),10)),{line:Math.max(0|o,1),column:Math.max(0|n,1)}}currentSourceFrame(){const e=t.Context.Context.instance().flavor(Ri);return e?e.currentSourceFrame():null}}var Ln=Object.freeze({__proto__:null,GoToLineQuickOpen:Tn});const Mn={formatS:"Format {PH1}",format:"Format"},Pn=e.i18n.registerUIStrings("panels/sources/InplaceFormatterEditorAction.ts",Mn),Fn=e.i18n.getLocalizedString.bind(void 0,Pn);let Dn;class Nn{button;sourcesView;constructor(){}static instance(e={forceNew:null}){const{forceNew:t}=e;return Dn&&!t||(Dn=new Nn),Dn}editorSelected(e){const t=e.data;this.updateButton(t)}editorClosed(e){const{wasSelected:t}=e.data;t&&this.updateButton(null)}updateButton(e){const t=this.isFormattable(e);this.button.element.classList.toggle("hidden",!t),e&&t&&this.button.setTitle(Fn(Mn.formatS,{PH1:e.name()}))}getOrCreateButton(e){return this.button||(this.sourcesView=e,this.sourcesView.addEventListener(Bi.EditorSelected,this.editorSelected.bind(this)),this.sourcesView.addEventListener(Bi.EditorClosed,this.editorClosed.bind(this)),this.button=new t.Toolbar.ToolbarButton(Fn(Mn.format),"brackets"),this.button.addEventListener(t.Toolbar.ToolbarButton.Events.Click,this.formatSourceInPlace,this),this.updateButton(e.currentUISourceCode())),this.button}isFormattable(e){return!!e&&(!!e.project().canSetFileContent()||null!==u.Persistence.PersistenceImpl.instance().binding(e))}formatSourceInPlace(){const e=this.sourcesView.currentUISourceCode();e&&this.isFormattable(e)&&(e.isDirty()?this.contentLoaded(e,e.workingCopy()):e.requestContent().then((t=>{this.contentLoaded(e,t.content||"")})))}async contentLoaded(e,t){const i=e.mimeType(),{formattedContent:o,formattedMapping:n}=await P.ScriptFormatter.format(e.contentType(),i,t);this.formattingComplete(e,o,n)}formattingComplete(e,t,i){if(e.workingCopy()===t)return;const o=this.sourcesView.viewForFile(e);let n=[0,0];if(o){const e=o.textEditor.toLineColumn(o.textEditor.state.selection.main.head);n=i.originalToFormatted(e.lineNumber,e.columnNumber)}e.setWorkingCopy(t),this.sourcesView.showSourceLocation(e,{lineNumber:n[0],columnNumber:n[1]})}}Oi(Nn.instance);var An=Object.freeze({__proto__:null,InplaceFormatterEditorAction:Nn});var Un=Object.freeze({__proto__:null,OpenFileQuickOpen:class extends In{attach(){this.setDefaultScores(Ri.defaultUISourceCodeScores()),super.attach()}uiSourceCodeSelected(e,t,o){a.userMetrics.actionTaken(a.UserMetrics.Action.SelectFileFromFilePicker),e&&("number"==typeof t?i.Revealer.reveal(e.uiLocation(t,o)):i.Revealer.reveal(e))}filterProject(e){return!e.isServiceProject()}renderItem(e,t,i,o){super.renderItem(e,t,i,o);const n=new r.Icon.Icon,s=F(this.itemContentTypeAt(e));n.data={...s,width:"20px",height:"20px"},i.parentElement?.parentElement?.insertBefore(n,i.parentElement)}renderAsTwoRows(){return!0}}});const Rn={noFileSelected:"No file selected.",openAJavascriptOrCssFileToSee:"Open a JavaScript or CSS file to see symbols",noResultsFound:"No results found"},Bn=e.i18n.registerUIStrings("panels/sources/OutlineQuickOpen.ts",Rn),Vn=e.i18n.getLocalizedString.bind(void 0,Bn);function On(e){function t(t){t=Math.max(0,Math.min(t,e.doc.length));const i=e.doc.lineAt(t);return{lineNumber:i.number-1,columnNumber:t-i.from}}function i(){for(;"ParamList"!==r.name&&r.nextSibling(););let t="";if("ParamList"===r.name&&r.firstChild())do{switch(r.name){case"ArrayPattern":t+="[‥]";break;case"ObjectPattern":t+="{‥}";break;case"VariableDefinition":t+=e.sliceDoc(r.from,r.to);break;case"Spread":t+="...";break;case",":t+=", "}}while(r.nextSibling());return`(${t})`}const o=[],r=n.syntaxTree(e).cursor();do{switch(r.name){case"RuleSet":for(r.firstChild();;r.nextSibling()){const i=e.sliceDoc(r.from,r.to),{lineNumber:n,columnNumber:s}=t(r.from);if(o.push({title:i,lineNumber:n,columnNumber:s}),r.nextSibling(),","!==r.name)break}break;case"FunctionDeclaration":case"MethodDeclaration":{let n="";r.firstChild();do{switch(r.name){case"abstract":case"async":case"get":case"set":case"static":n=`${n}${r.name} `;break;case"Star":n+="*";break;case"PropertyDefinition":case"VariableDefinition":{const s=n+e.sliceDoc(r.from,r.to),{lineNumber:a,columnNumber:c}=t(r.from),l=i();o.push({title:s,subtitle:l,lineNumber:a,columnNumber:c});break}}}while(r.nextSibling());break}case"Property":{let n="";r.firstChild();do{if("async"===r.name||"get"===r.name||"set"===r.name)n=`${n}${r.name} `;else{if("Star"!==r.name){if("PropertyDefinition"===r.name){let s=e.sliceDoc(r.from,r.to);const{lineNumber:a,columnNumber:c}=t(r.from);for(;r.nextSibling();){if("ClassExpression"===r.name){s=`class ${s}`,o.push({title:s,lineNumber:a,columnNumber:c});break}if("ArrowFunction"!==r.name&&"FunctionExpression"!==r.name||r.firstChild(),"async"===r.name)n=`async ${n}`;else if("Star"===r.name)n+="*";else if("ParamList"===r.name){s=n+s;const e=i();o.push({title:s,subtitle:e,lineNumber:a,columnNumber:c});break}}break}break}n+="*"}}while(r.nextSibling());break}case"PropertyName":case"VariableDefinition":if(r.matchContext(["ClassDeclaration"])){const i="class "+e.sliceDoc(r.from,r.to),{lineNumber:n,columnNumber:s}=t(r.from);o.push({title:i,lineNumber:n,columnNumber:s})}else if(r.matchContext(["AssignmentExpression","MemberExpression"])||r.matchContext(["VariableDeclaration"])){let n=e.sliceDoc(r.from,r.to);const{lineNumber:s,columnNumber:a}=t(r.from);for(;"Equals"!==r.name&&r.next(););if(!r.nextSibling())break;if("ArrowFunction"===r.name||"FunctionExpression"===r.name){r.firstChild();let e="";for(;"ParamList"!==r.name&&("async"===r.name?e=`async ${e}`:"Star"===r.name&&(e+="*"),r.nextSibling()););n=e+n;const t=i();o.push({title:n,subtitle:t,lineNumber:s,columnNumber:a})}else"ClassExpression"===r.name&&(n=`class ${n}`,o.push({title:n,lineNumber:s,columnNumber:a}))}break;case"App":if(r.firstChild()&&r.nextSibling()&&"module"===e.sliceDoc(r.from,r.to)){if(r.nextSibling()&&"Identifier"===r.name){const i=e.sliceDoc(r.from,r.to),{lineNumber:n,columnNumber:s}=t(r.from);o.push({title:i,lineNumber:n,columnNumber:s})}do{if("App"===r.name&&r.firstChild()){if(r.nextSibling()&&"func"===e.sliceDoc(r.from,r.to)&&r.nextSibling()&&"Identifier"===r.name){const i=e.sliceDoc(r.from,r.to),{lineNumber:n,columnNumber:s}=t(r.from),a=[];for(;r.nextSibling();)"App"===r.name&&r.firstChild()&&(r.nextSibling()&&"param"===e.sliceDoc(r.from,r.to)&&(r.nextSibling()&&"Identifier"===r.name?a.push(e.sliceDoc(r.from,r.to)):a.push(`$${a.length}`)),r.parent());const c=`(${a.join(", ")})`;o.push({title:i,subtitle:c,lineNumber:n,columnNumber:s})}r.parent()}}while(r.nextSibling())}break;case"FieldIdentifier":case"Identifier":if(r.matchContext(["FunctionDeclarator"])){const i=e.sliceDoc(r.from,r.to),{lineNumber:n,columnNumber:s}=t(r.from);o.push({title:i,lineNumber:n,columnNumber:s})}break;case"TypeIdentifier":if(r.matchContext(["ClassSpecifier"])){const i=`class ${e.sliceDoc(r.from,r.to)}`,{lineNumber:n,columnNumber:s}=t(r.from);o.push({title:i,lineNumber:n,columnNumber:s})}else if(r.matchContext(["StructSpecifier"])){const i=`struct ${e.sliceDoc(r.from,r.to)}`,{lineNumber:n,columnNumber:s}=t(r.from);o.push({title:i,lineNumber:n,columnNumber:s})}}}while(r.next());return o}class Wn extends k.FilteredListWidget.Provider{items=[];active=!1;attach(){const e=this.currentSourceFrame();e?(this.active=!0,this.items=On(e.textEditor.state).map((({title:t,subtitle:i,lineNumber:o,columnNumber:n})=>(({lineNumber:o,columnNumber:n}=e.editorLocationToUILocation(o,n)),{title:t,subtitle:i,lineNumber:o,columnNumber:n})))):(this.active=!1,this.items=[])}detach(){this.active=!1,this.items=[]}itemCount(){return this.items.length}itemKeyAt(e){const t=this.items[e];return t.title+(t.subtitle?t.subtitle:"")}itemScoreAt(e,t){const i=this.items[e];return t.split("(")[0].toLowerCase()===i.title.toLowerCase()?1/(1+i.lineNumber):-i.lineNumber-1}renderItem(e,t,i,o){const n=this.items[e];i.textContent=n.title+(n.subtitle?n.subtitle:""),k.FilteredListWidget.FilteredListWidget.highlightRanges(i,t);const r=this.currentSourceFrame();if(!r)return;const s=i.parentElement?.parentElement?.createChild("span","tag");if(!s)return;const a=r.wasmDisassembly;if(a){const e=a.lineNumberToBytecodeOffset(a.lineNumbers-1).toString(16).length;s.textContent=`:0x${n.columnNumber.toString(16).padStart(e,"0")}`}else s.textContent=`:${n.lineNumber+1}`}selectItem(e,t){if(null===e)return;const i=this.currentSourceFrame();if(!i)return;const o=this.items[e];i.revealPosition({lineNumber:o.lineNumber,columnNumber:o.columnNumber},!0)}currentSourceFrame(){const e=t.Context.Context.instance().flavor(Ri);return e&&e.currentSourceFrame()}notFoundText(){return this.currentSourceFrame()?this.active?Vn(Rn.noResultsFound):Vn(Rn.openAJavascriptOrCssFileToSee):Vn(Rn.noFileSelected)}}var jn=Object.freeze({__proto__:null,outline:On,OutlineQuickOpen:Wn});const Hn=new CSSStyleSheet;Hn.replaceSync(".scope-chain-sidebar-pane-section-header{flex:auto}.scope-chain-sidebar-pane-section-icon{float:left;margin-right:5px}.scope-chain-sidebar-pane-section-subtitle{float:right;margin-left:5px;max-width:55%;text-overflow:ellipsis;overflow:hidden}.scope-chain-sidebar-pane-section-title{font-weight:normal;word-wrap:break-word;white-space:normal}.scope-chain-sidebar-pane-section{padding:2px 4px;flex:none}\n/*# sourceURL=scopeChainSidebarPane.css */\n");const _n={loading:"Loading...",notPaused:"Not paused",noVariables:"No variables",closureS:"Closure ({PH1})",closure:"Closure",exception:"Exception",returnValue:"Return value",revealInMemoryInspectorPanel:"Reveal in Memory Inspector panel"},zn=e.i18n.registerUIStrings("panels/sources/ScopeChainSidebarPane.ts",_n),qn=e.i18n.getLocalizedString.bind(void 0,zn);let Gn,$n;class Kn extends t.Widget.VBox{treeOutline;expandController;linkifier;infoElement;#x=null;constructor(){super(!0),this.treeOutline=new C.ObjectPropertiesSection.ObjectPropertiesSectionsTreeOutline,this.treeOutline.setShowSelectionOnKeyboardFocus(!0),this.expandController=new C.ObjectPropertiesSection.ObjectPropertiesSectionsTreeExpandController(this.treeOutline),this.linkifier=new M.Linkifier.Linkifier,this.infoElement=document.createElement("div"),this.infoElement.className="gray-info-message",this.infoElement.tabIndex=-1,o.TargetManager.TargetManager.instance().addModelListener(o.DebuggerModel.DebuggerModel,o.DebuggerModel.Events.DebugInfoAttached,this.debugInfoAttached,this),this.update()}static instance(){return Gn||(Gn=new Kn),Gn}flavorChanged(e){this.update()}focus(){this.hasFocus()||t.Context.Context.instance().flavor(o.DebuggerModel.DebuggerPausedDetails)&&this.treeOutline.forceSelect()}sourceMapAttached(e){e.data.client===this.#x&&this.update()}setScopeSourceMapSubscription(e){const t=this.#x;this.#x=e?.script??null,t?.debuggerModel!==this.#x?.debuggerModel&&(t&&t.debuggerModel.sourceMapManager().removeEventListener(o.SourceMapManager.Events.SourceMapAttached,this.sourceMapAttached,this),this.#x&&this.#x.debuggerModel.sourceMapManager().addEventListener(o.SourceMapManager.Events.SourceMapAttached,this.sourceMapAttached,this))}debugInfoAttached(e){e.data===this.#x&&this.update()}async update(){this.infoElement.textContent=qn(_n.loading),this.contentElement.removeChildren(),this.contentElement.appendChild(this.infoElement),this.linkifier.reset();const e=t.Context.Context.instance().flavor(o.DebuggerModel.CallFrame);this.setScopeSourceMapSubscription(e);const[i,n]=await Promise.all([h.NamesResolver.resolveThisObject(e),h.NamesResolver.resolveScopeChain(e)]);if(e===t.Context.Context.instance().flavor(o.DebuggerModel.CallFrame)){const r=t.Context.Context.instance().flavor(o.DebuggerModel.DebuggerPausedDetails);if(this.treeOutline.removeChildren(),!r||!e||!n)return void(this.infoElement.textContent=qn(_n.notPaused));this.contentElement.removeChildren(),this.contentElement.appendChild(this.treeOutline.element);let s=!1;for(let t=0;t<n.length;++t){const o=n[t],a=this.extraPropertiesForScope(o,r,e,i,0===t);"local"===o.type()&&(s=!0);const c=this.createScopeSectionTreeElement(o,a);"global"===o.type()?c.collapse():s&&"local"!==o.type()||c.expand(),this.treeOutline.appendChild(c),0===t&&c.select(!0)}this.sidebarPaneUpdatedForTest()}}createScopeSectionTreeElement(e,i){let o=null;e.type(),o=qn(_n.noVariables);let n=e.typeName();if("closure"===e.type()){const i=e.name();n=i?qn(_n.closureS,{PH1:t.UIUtils.beautifyFunctionName(i)}):qn(_n.closure)}let r=e.description();n&&n!==r||(r=null);const s=e.icon(),a=document.createElement("div");if(a.classList.add("scope-chain-sidebar-pane-section-header"),a.classList.add("tree-element-title"),s){const e=document.createElement("img");e.classList.add("scope-chain-sidebar-pane-section-icon"),e.src=s,a.appendChild(e)}a.createChild("div","scope-chain-sidebar-pane-section-subtitle").textContent=r,a.createChild("div","scope-chain-sidebar-pane-section-title").textContent=n;const c=new C.ObjectPropertiesSection.RootElement(h.NamesResolver.resolveScopeInObject(e),this.linkifier,o,0,i);return c.title=a,c.listItemElement.classList.add("scope-chain-sidebar-pane-section"),c.listItemElement.setAttribute("aria-label",n),this.expandController.watchSection(n+(r?":"+r:""),c),c}extraPropertiesForScope(e,t,i,n,r){if("local"!==e.type()||i.script.isWasm())return[];const s=[];if(n&&s.push(new o.RemoteObject.RemoteObjectProperty("this",n,void 0,void 0,void 0,void 0,void 0,!0)),r){const e=t.exception();e&&s.push(new o.RemoteObject.RemoteObjectProperty(qn(_n.exception),e,void 0,void 0,void 0,void 0,void 0,!0));const n=i.returnValue();n&&s.push(new o.RemoteObject.RemoteObjectProperty(qn(_n.returnValue),n,void 0,void 0,void 0,void 0,void 0,!0,i.setReturnValue.bind(i)))}return s}sidebarPaneUpdatedForTest(){}wasShown(){super.wasShown(),this.treeOutline.registerCSSFiles([Hn]),this.registerCSSFiles([Hn])}}class Jn extends t.Widget.VBox{static instance(e={forceNew:null}){const{forceNew:t}=e;return $n&&!t||($n=new Jn),$n}appendApplicableItems(e,t,i){if(i instanceof C.ObjectPropertiesSection.ObjectPropertyTreeElement&&i.property&&i.property.value&&D.LinearMemoryInspectorController.isMemoryObjectProperty(i.property.value)){const e=i.path();t.debugSection().appendItem(qn(_n.revealInMemoryInspectorPanel),this.openMemoryInspector.bind(this,e,i.property.value))}}async openMemoryInspector(e,t){const i=D.LinearMemoryInspectorController.LinearMemoryInspectorController.instance();a.userMetrics.linearMemoryInspectorRevealedFrom(a.UserMetrics.LinearMemoryInspectorRevealedFrom.ContextMenu),i.openInspectorView(t,void 0,e)}}var Yn=Object.freeze({__proto__:null,ScopeChainSidebarPane:Kn,OpenLinearMemoryInspector:Jn});const Xn=new CSSStyleSheet;Xn.replaceSync(".value.object-value-node:hover{background-color:var(--item-hover-color)}.object-value-function-prefix,\n.object-value-boolean{color:var(--color-syntax-3)}.object-value-function{font-style:italic}.object-value-function.linkified:hover{--override-linkified-hover-background:rgb(0 0 0/10%);background-color:var(--override-linkified-hover-background);cursor:pointer}.-theme-with-dark-background .object-value-function.linkified:hover,\n:host-context(.-theme-with-dark-background) .object-value-function.linkified:hover{--override-linkified-hover-background:rgb(230 230 230/10%)}.object-value-number{color:var(--color-syntax-3)}.object-value-bigint{color:var(--color-syntax-6)}.object-value-string,\n.object-value-regexp,\n.object-value-symbol{white-space:pre;unicode-bidi:-webkit-isolate;color:var(--color-syntax-1)}.object-value-node{position:relative;vertical-align:baseline;color:var(--color-syntax-7);white-space:nowrap}.object-value-null,\n.object-value-undefined{color:var(--color-text-disabled)}.object-value-unavailable{color:var(--color-syntax-2)}.object-value-calculate-value-button:hover{text-decoration:underline}.object-properties-section-custom-section{display:inline-flex;flex-direction:column}.-theme-with-dark-background .object-value-number,\n:host-context(.-theme-with-dark-background) .object-value-number,\n.-theme-with-dark-background .object-value-boolean,\n:host-context(.-theme-with-dark-background) .object-value-boolean{--override-primitive-dark-mode-color:hsl(252deg 100% 75%);color:var(--override-primitive-dark-mode-color)}.object-properties-section .object-description{color:var(--color-text-secondary)}.value .object-properties-preview{white-space:nowrap}.name{color:var(--color-syntax-2);flex-shrink:0}.object-properties-preview .name{color:var(--color-text-secondary)}@media (forced-colors: active){.object-value-calculate-value-button:hover{forced-color-adjust:none;color:Highlight}}\n/*# sourceURL=objectValue.css */\n");const Qn=new CSSStyleSheet;Qn.replaceSync(".watch-expression-delete-button{position:absolute;opacity:0%;background-color:var(--icon-default);cursor:pointer}.watch-expression-delete-button:hover{background-color:var(--icon-default-hover)}:host-context(.-theme-with-dark-background) .watch-expression-delete-button{filter:brightness(1.5)}.right-aligned{right:16px}.left-aligned{left:-11px}.watch-expression-title:hover .watch-expression-delete-button{opacity:100%}.watch-expressions{overflow-x:hidden;min-height:26px}.watch-expression-title{white-space:nowrap;line-height:20px;display:flex}.watch-expression-title:hover{padding-right:26px}.watch-expression-object-header .watch-expression-title{margin-left:1px}.watch-expression{position:relative;flex:auto;min-height:20px}.watch-expression .name{--override-watch-expression-name-color:rgb(136 19 145);color:var(--override-watch-expression-name-color);flex:none;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;flex-shrink:2}.-theme-with-dark-background .watch-expression .name,\n:host-context(.-theme-with-dark-background) .watch-expression .name{--override-watch-expression-name-color:rgb(227 110 236)}.watch-expression-error{color:var(--color-red)}.watch-expressions-separator{flex:none}.watch-expression .value{white-space:nowrap;display:inline;overflow:hidden;padding-left:4px;text-overflow:ellipsis;flex-shrink:1}.watch-expression .text-prompt{text-overflow:clip;overflow:hidden;white-space:nowrap;padding-left:4px;min-height:18px;line-height:18px;user-select:text}.watch-expression-text-prompt-proxy{margin:2px 12px 2px -4px;padding-bottom:3px}.watch-expression-header{flex:auto;margin-left:-16px;padding-left:15px}li.watch-expression-tree-item{padding-left:4px}li.watch-expression-tree-item:hover{background-color:var(--color-background-elevation-1)}.watch-expression-header:focus-visible{background:var(--legacy-focus-bg-color)}li.watch-expression-editing::before{background-color:transparent}@media (forced-colors: active){.watch-expression-title:hover .watch-expression-delete-button,\n  .watch-expressions .dimmed{opacity:100%}li.watch-expression-tree-item *{forced-color-adjust:none;color:ButtonText}li.watch-expression-tree-item:hover{forced-color-adjust:none;background-color:Highlight}li.watch-expression-tree-item:hover *{color:HighlightText}li.watch-expression-tree-item:hover .watch-expression-delete-button{background-color:HighlightText}}\n/*# sourceURL=watchExpressionsSidebarPane.css */\n");const Zn={addWatchExpression:"Add watch expression",refreshWatchExpressions:"Refresh watch expressions",noWatchExpressions:"No watch expressions",deleteAllWatchExpressions:"Delete all watch expressions",addPropertyPathToWatch:"Add property path to watch",deleteWatchExpression:"Delete watch expression",notAvailable:"<not available>",copyValue:"Copy value"},er=e.i18n.registerUIStrings("panels/sources/WatchExpressionsSidebarPane.ts",Zn),tr=e.i18n.getLocalizedString.bind(void 0,er);let ir;class or extends t.ThrottledWidget.ThrottledWidget{watchExpressions;emptyElement;watchExpressionsSetting;addButton;refreshButton;treeOutline;expandController;linkifier;constructor(){super(!0),this.watchExpressions=[],this.watchExpressionsSetting=i.Settings.Settings.instance().createLocalSetting("watchExpressions",[]),this.addButton=new t.Toolbar.ToolbarButton(tr(Zn.addWatchExpression),"plus"),this.addButton.addEventListener(t.Toolbar.ToolbarButton.Events.Click,(e=>{this.addButtonClicked()})),this.refreshButton=new t.Toolbar.ToolbarButton(tr(Zn.refreshWatchExpressions),"refresh"),this.refreshButton.addEventListener(t.Toolbar.ToolbarButton.Events.Click,this.update,this),this.contentElement.classList.add("watch-expressions"),this.contentElement.addEventListener("contextmenu",this.contextMenu.bind(this),!1),this.treeOutline=new C.ObjectPropertiesSection.ObjectPropertiesSectionsTreeOutline,this.treeOutline.setShowSelectionOnKeyboardFocus(!0),this.expandController=new C.ObjectPropertiesSection.ObjectPropertiesSectionsTreeExpandController(this.treeOutline),t.Context.Context.instance().addFlavorChangeListener(o.RuntimeModel.ExecutionContext,this.update,this),t.Context.Context.instance().addFlavorChangeListener(o.DebuggerModel.CallFrame,this.update,this),this.linkifier=new M.Linkifier.Linkifier,this.update()}static instance(){return ir||(ir=new or),ir}toolbarItems(){return[this.addButton,this.refreshButton]}focus(){this.hasFocus()||this.watchExpressions.length>0&&this.treeOutline.forceSelect()}hasExpressions(){return Boolean(this.watchExpressionsSetting.get().length)}saveExpressions(){const e=[];for(let t=0;t<this.watchExpressions.length;t++){const i=this.watchExpressions[t].expression();i&&e.push(i)}this.watchExpressionsSetting.set(e)}async addButtonClicked(){await t.ViewManager.ViewManager.instance().showView("sources.watch"),this.emptyElement.classList.add("hidden"),this.createWatchExpression(null).startEditing()}async doUpdate(){this.linkifier.reset(),this.contentElement.removeChildren(),this.treeOutline.removeChildren(),this.watchExpressions=[],this.emptyElement=this.contentElement.createChild("div","gray-info-message"),this.emptyElement.textContent=tr(Zn.noWatchExpressions),this.emptyElement.tabIndex=-1;const e=this.watchExpressionsSetting.get();e.length&&this.emptyElement.classList.add("hidden");for(let t=0;t<e.length;++t){const i=e[t];i&&this.createWatchExpression(i)}}createWatchExpression(e){this.contentElement.appendChild(this.treeOutline.element);const t=new nr(e,this.expandController,this.linkifier);return t.addEventListener("ExpressionUpdated",this.watchExpressionUpdated,this),this.treeOutline.appendChild(t.treeElement()),this.watchExpressions.push(t),t}watchExpressionUpdated({data:e}){e.expression()||(c.ArrayUtilities.removeElement(this.watchExpressions,e),this.treeOutline.removeChild(e.treeElement()),this.emptyElement.classList.toggle("hidden",Boolean(this.watchExpressions.length)),0===this.watchExpressions.length&&this.treeOutline.element.remove()),this.saveExpressions()}contextMenu(e){const i=new t.ContextMenu.ContextMenu(e);this.populateContextMenu(i,e),i.show()}populateContextMenu(e,t){let i=!1;for(const e of this.watchExpressions)i=i||e.isEditing();i||e.debugSection().appendItem(tr(Zn.addWatchExpression),this.addButtonClicked.bind(this)),this.watchExpressions.length>1&&e.debugSection().appendItem(tr(Zn.deleteAllWatchExpressions),this.deleteAllButtonClicked.bind(this));const o=this.treeOutline.treeElementFromEvent(t);if(!o)return;const n=this.watchExpressions.find((e=>o.hasAncestorOrSelf(e.treeElement())));n&&n.populateContextMenu(e,t)}deleteAllButtonClicked(){this.watchExpressions=[],this.saveExpressions(),this.update()}async focusAndAddExpressionToWatch(e){await t.ViewManager.ViewManager.instance().showView("sources.watch"),this.createWatchExpression(e),this.saveExpressions(),this.update()}handleAction(e,i){const o=t.Context.Context.instance().flavor(si);if(!o)return!1;const{state:n}=o.textEditor,r=n.sliceDoc(n.selection.main.from,n.selection.main.to);return this.focusAndAddExpressionToWatch(r),!0}appendApplicableItems(e,i,o){o instanceof C.ObjectPropertiesSection.ObjectPropertyTreeElement&&!o.property.synthetic&&i.debugSection().appendItem(tr(Zn.addPropertyPathToWatch),(()=>this.focusAndAddExpressionToWatch(o.path())));const n=t.Context.Context.instance().flavor(si);n&&!n.textEditor.state.selection.main.empty&&i.debugSection().appendAction("sources.add-to-watch")}wasShown(){super.wasShown(),this.treeOutline.registerCSSFiles([Qn]),this.registerCSSFiles([Qn,Xn])}}class nr extends i.ObjectWrapper.ObjectWrapper{treeElementInternal;nameElement;valueElement;expressionInternal;expandController;element;editing;linkifier;textPrompt;result;preventClickTimeout;resizeObserver;constructor(e,t,i){super(),this.expressionInternal=e,this.expandController=t,this.element=document.createElement("div"),this.element.classList.add("watch-expression"),this.element.classList.add("monospace"),this.editing=!1,this.linkifier=i,this.createWatchExpression(),this.update()}treeElement(){return this.treeElementInternal}expression(){return this.expressionInternal}async#y(e,t){if(I.Runtime.experiments.isEnabled("evaluateExpressionsWithSourceMaps")){const i=e.debuggerModel.selectedCallFrame();if(i){const e=await h.NamesResolver.allVariablesInCallFrame(i);try{t=await P.FormatterWorkerPool.formatterWorkerPool().javaScriptSubstitute(t,e)}catch{}}}return e.evaluate({expression:t,objectGroup:nr.watchObjectGroupId,includeCommandLineAPI:!1,silent:!0,returnByValue:!1,generatePreview:!1},!1,!1)}update(){const e=t.Context.Context.instance().flavor(o.RuntimeModel.ExecutionContext);e&&this.expressionInternal?this.#y(e,this.expressionInternal).then((e=>{"object"in e?this.createWatchExpression(e.object,e.exceptionDetails):this.createWatchExpression()})):this.createWatchExpression()}startEditing(){this.editing=!0,this.treeElementInternal.setDisableSelectFocus(!0),this.element.removeChildren();const e=this.element.createChild("div");e.textContent=this.nameElement.textContent,this.textPrompt=new C.ObjectPropertiesSection.ObjectPropertyPrompt,this.textPrompt.renderAsBlock();const t=this.textPrompt.attachAndStartEditing(e,this.finishEditing.bind(this));this.treeElementInternal.listItemElement.classList.add("watch-expression-editing"),this.treeElementInternal.collapse(),t.classList.add("watch-expression-text-prompt-proxy"),t.addEventListener("keydown",this.promptKeyDown.bind(this),!1);const i=this.element.getComponentSelection();i&&i.selectAllChildren(e)}isEditing(){return Boolean(this.editing)}finishEditing(e,t){if(e&&e.consume(t),this.editing=!1,this.treeElementInternal.setDisableSelectFocus(!1),this.treeElementInternal.listItemElement.classList.remove("watch-expression-editing"),this.textPrompt){this.textPrompt.detach();const e=t?this.expressionInternal:this.textPrompt.text();this.textPrompt=void 0,this.element.removeChildren(),this.updateExpression(e)}}dblClickOnWatchExpression(e){e.consume(),this.isEditing()||this.startEditing()}updateExpression(e){this.expressionInternal&&this.expandController.stopWatchSectionsWithId(this.expressionInternal),this.resizeObserver?.disconnect(),this.expressionInternal=e,this.update(),this.dispatchEventToListeners("ExpressionUpdated",this)}deleteWatchExpression(e){e.consume(!0),this.updateExpression(null)}createWatchExpression(e,t){this.result=e||null,this.element.removeChildren();const i=this.treeElementInternal;if(this.createWatchExpressionTreeElement(e,t),i&&i.parent){const e=i.parent,t=e.indexOfChild(i);e.removeChild(i),e.insertChild(this.treeElementInternal,t)}this.treeElementInternal.select()}createWatchExpressionHeader(e,i){const o=this.element.createChild("div","watch-expression-header"),n=t.Icon.Icon.create("cross","watch-expression-delete-button");this.resizeObserver=new ResizeObserver((e=>{e.forEach((e=>{e.contentRect.width<55?(n.classList.remove("right-aligned"),n.classList.add("left-aligned")):(n.classList.remove("left-aligned"),n.classList.add("right-aligned"))}))})),this.resizeObserver.observe(o),t.Tooltip.Tooltip.install(n,tr(Zn.deleteWatchExpression)),n.addEventListener("click",this.deleteWatchExpression.bind(this),!1);const r=o.createChild("div","watch-expression-title tree-element-title");if(r.appendChild(n),this.nameElement=C.ObjectPropertiesSection.ObjectPropertiesSection.createNameElement(this.expressionInternal),Boolean(i)||!e)this.valueElement=document.createElement("span"),this.valueElement.classList.add("watch-expression-error"),this.valueElement.classList.add("value"),r.classList.add("dimmed"),this.valueElement.textContent=tr(Zn.notAvailable),void 0!==i&&void 0!==i.exception&&void 0!==i.exception.description&&t.Tooltip.Tooltip.install(this.valueElement,i.exception.description);else{const t=C.ObjectPropertiesSection.ObjectPropertiesSection.createPropertyValueWithCustomSupport(e,Boolean(i),!1,r,this.linkifier);this.valueElement=t.element}const s=document.createElement("span");return s.classList.add("watch-expressions-separator"),s.textContent=": ",r.append(this.nameElement,s,this.valueElement),o}createWatchExpressionTreeElement(e,i){const o=this.createWatchExpressionHeader(e,i);!i&&e&&e.hasChildren&&!e.customPreview()?(o.classList.add("watch-expression-object-header"),this.treeElementInternal=new C.ObjectPropertiesSection.RootElement(e,this.linkifier),this.expandController.watchSection(this.expressionInternal,this.treeElementInternal),this.treeElementInternal.toggleOnClick=!1,this.treeElementInternal.listItemElement.addEventListener("click",this.onSectionClick.bind(this),!1),this.treeElementInternal.listItemElement.addEventListener("dblclick",this.dblClickOnWatchExpression.bind(this))):(o.addEventListener("dblclick",this.dblClickOnWatchExpression.bind(this)),this.treeElementInternal=new t.TreeOutline.TreeElement),this.treeElementInternal.title=this.element,this.treeElementInternal.listItemElement.classList.add("watch-expression-tree-item"),this.treeElementInternal.listItemElement.addEventListener("keydown",(e=>{"Enter"!==e.key||this.isEditing()?"Delete"!==e.key||this.isEditing()||this.deleteWatchExpression(e):(this.startEditing(),e.consume(!0))}))}onSectionClick(e){e.consume(!0);1===e.detail?this.preventClickTimeout=window.setTimeout(function(){if(!this.treeElementInternal)return;this.treeElementInternal.expanded?this.treeElementInternal.collapse():this.editing||this.treeElementInternal.expand()}.bind(this),333):void 0!==this.preventClickTimeout&&(window.clearTimeout(this.preventClickTimeout),this.preventClickTimeout=void 0)}promptKeyDown(e){const t=c.KeyboardUtilities.isEscKey(e);("Enter"===e.key||t)&&this.finishEditing(e,t)}populateContextMenu(e,i){this.isEditing()||e.editSection().appendItem(tr(Zn.deleteWatchExpression),this.updateExpression.bind(this,null)),this.isEditing()||!this.result||"number"!==this.result.type&&"string"!==this.result.type||e.clipboardSection().appendItem(tr(Zn.copyValue),this.copyValueButtonClicked.bind(this));const o=t.UIUtils.deepElementFromEvent(i);o&&this.valueElement.isSelfOrAncestor(o)&&this.result&&e.appendApplicableItems(this.result)}copyValueButtonClicked(){a.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(this.valueElement.textContent)}static watchObjectGroupId="watch-group"}var rr=Object.freeze({__proto__:null,WatchExpressionsSidebarPane:or,WatchExpression:nr});export{V as AddSourceMapURLDialog,q as BreakpointEditDialog,Ue as CSSPlugin,ne as CallStackSidebarPane,Se as CoveragePlugin,_e as DebuggerPausedMessage,bn as DebuggerPlugin,Ut as EditingLocationHistoryManager,Sn as FilePathScoreFunction,xn as FilteredUISourceCodeListProvider,Ln as GoToLineQuickOpen,An as InplaceFormatterEditorAction,mt as NavigatorView,Un as OpenFileQuickOpen,jn as OutlineQuickOpen,se as Plugin,Zt as ResourceOriginPlugin,Yn as ScopeChainSidebarPane,et as SearchSourcesView,ri as SnippetsPlugin,Dt as SourcesNavigator,Eo as SourcesPanel,Je as SourcesSearchScope,$i as SourcesView,Di as TabbedEditorContainer,eo as ThreadsSidebarPane,Ci as UISourceCodeFrame,rr as WatchExpressionsSidebarPane};
